我想从文件中提取特定行(比如第 2 行和第 4 到 6 行)并将它们重定向到命令行中的文件/将其通过管道传输到另一个程序。
哪个工具能最快/最干净地完成这项工作(sed、awk、perl、shell)?
Sed 有一个很好的方法:
sed -ne '2p' -e '4,6p'
例如:
$ printf '%s\n' {1..100} | sed -ne '2p' -e '4,6p'
2
4
5
6
使用awk
及其参数NR
。您可以编写条件表达式,例如:
$ 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
等等
在你的情况下,
$ awk 'NR==2; NR>=4 && NR<=6' a #print line number 2 and from 4 to 6
awk 'NR==2 || NR>=4 && NR<=6'
或者
awk 'NR==2; NR==4,NR==6'
Use awk and keep it clear and simple:
awk 'NR==2 || (NR>=4 && NR<=6)' file
您可以使用 justhead
和tail
...
例如:
NR=3; cat test.txt | head -n $NR | tail -n -1
test.txt
从;中提取第 3 行 和
NB=2; NR=3; cat test.txt | head -n $(expr $NR \+ $NB) | tail -n -$NB
提取第 3 到 5 行。