Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

head and grep simultaneously

Is there a unix one liner to do this?

head -n 3 test.txt > out_dir/test.head.txt
grep hello test.txt > out_dir/test.tmp.txt
cat out_dir/test.head.txt out_dir/test.tmp.txt > out_dir/test.hello.txt
rm out_dir/test.head.txt out_dir/test.tmp.txt

I.e., I want to get the header and some grep lines from a given file, simultaneously.

like image 533
Dnaiel Avatar asked Nov 12 '13 18:11

Dnaiel


3 Answers

Use awk:

awk 'NR<=3 || /hello/' test.txt > out_dir/test.hello.txt
like image 115
anubhava Avatar answered Oct 02 '22 08:10

anubhava


You can say:

{ head -n 3 test.txt ; grep hello test.txt ; } > out_dir/test.hello.txt
like image 45
devnull Avatar answered Oct 02 '22 07:10

devnull


Try using sed

sed -n '1,3p; /hello/p' test.txt > out_dir/test.hello.txt
like image 24
jkshah Avatar answered Oct 02 '22 08:10

jkshah