help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Printing arbitrary line range from files


From: lisa-asket
Subject: Printing arbitrary line range from files
Date: Mon, 28 Jun 2021 18:10:34 +0200 (CEST)



From: Greg Wooledge <greg@wooledge.org>
To: help-bash@gnu.org
Subject: Re: Printing arbitrary line range from files
Date: 28/06/2021 13:24:46 Europe/Paris

On Mon, Jun 28, 2021 at 10:21:28AM +0200, lisa-asket@perso.be wrote:
> But I want to return lines $na trough $nb from each file matched.

Please STOP top-posting.

If this means you need to stop using whatever Microsoft Windows-based
or web-based mail user agent is preventing you from posting correctly,
then do that too.

> > print-lines 5 8 .
> > 
> > print-lines ()
> >   {
> >     na=$1
> >     nb=$2
> >     dir=$3
> > 
> >     find "$dir" \( -name \*.org -o -name \*.texi \)  \
> >       | xargs sed -n "$na,${nb}p"
> >   }

find "$dir" \( ... \) -exec sed -n "$na,${nb}p" {} \;

xargs is not your friend here.

If you'd like to process more than one file at a time, switch from sed
to some other solution, such as awk.

unicorn:~$ printf %s\\n a b c d e f > foo
unicorn:~$ printf %s\\n 1 2 3 4 5 6 > bar
unicorn:~$ awk -v a=2 -v b=4 'FNR >= a && FNR <= b' foo bar
b
c
d
2
3
4

Is that what you want? Then you can do that.

print-lines() {
if (($# != 3)); then
echo 'usage: print-lines startnum endnum startdir' >&2
return 1
fi

find "$3" \( ... \) \
-exec awk -v a="$1" -v b="$2" 'FNR >= a && FNR <= b' {} +
}

As I said yesterday, there are many alternatives and optimizations
available, including optimizations that stop reading input once you
reach the last line you care about. (All the solutions we've
discussed on the mailing list, so far, will read the entire input
file.)

xargs continues not being your friend here too, by the way. find's
-exec + makes xargs largely obsolete, and without GNU/BSD extensions,
xargs can't even handle common filenames.


* Your awk command does as I wish.  How can I add the file name before each
output?   




reply via email to

[Prev in Thread] Current Thread [Next in Thread]