I want to extract specific lines (say lines 2, and 4 through 6) from a file and redirect them to a file in the command line / pipe it to another program.
Which tool would do the job the fastest / cleanest (sed, awk, perl, shell)?
I want to extract specific lines (say lines 2, and 4 through 6) from a file and redirect them to a file in the command line / pipe it to another program.
Which tool would do the job the fastest / cleanest (sed, awk, perl, shell)?
Sed has a nice way of doing this:
sed -ne '2p' -e '4,6p'
for example:
$ printf '%s\n' {1..100} | sed -ne '2p' -e '4,6p'
2
4
5
6
Use awk
and its parameter NR
. You can compose conditional expressions such as:
$ cat a
aa
bb
cc
dd
ee
$ awk 'NR==3' a #print line number 3
cc
$ awk 'NR==3, NR==5' a #print from line number 3 up to number 5
cc
dd
ee
$ awk 'NR>2 && NR<7' a #print lines whose number is in the range (2,7)
cc
dd
ee
etc.
In your case,
$ awk 'NR==2; NR>=4 && NR<=6' a #print line number 2 and from 4 to 6
You can do it using just head
and tail
...
For example:
NR=3; cat test.txt | head -n $NR | tail -n -1
extracts line 3 from test.txt
; and
NB=2; NR=3; cat test.txt | head -n $(expr $NR \+ $NB) | tail -n -$NB
extracts line 3 to 5.
Use awk and keep it clear and simple:
awk 'NR==2 || (NR>=4 && NR<=6)' file