Search code examples
bashunixgrepunix-head

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.


Solution

  • Use awk:

    awk 'NR<=3 || /hello/' test.txt > out_dir/test.hello.txt