头和grep同时

Dna*_*iel 4 unix bash grep unix-head

是否有一个unix one liner来做这件事?

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
Run Code Online (Sandbox Code Playgroud)

即,我想同时从给定文件中获取标题和一些grep行.

dev*_*ull 8

你可以说:

{ head -n 3 test.txt ; grep hello test.txt ; } > out_dir/test.hello.txt
Run Code Online (Sandbox Code Playgroud)


anu*_*ava 8

使用awk:

awk 'NR<=3 || /hello/' test.txt > out_dir/test.hello.txt
Run Code Online (Sandbox Code Playgroud)