Friday, February 18, 2022

[SOLVED] Include header in the 'grep' result

Issue

Is there a way to combine 'head -1' and 'grep' command into one for all the files in a directory and redirect the output to an output file. I can do this using 'sed' but it seems that it is not as fast as grep.

sed -n '1p;/6330162/p' infile*.txt > outfile.txt

Using grep I can do the following one file at a time:

head -1 infile1.txt;  grep -i '6330162' infile1.txt > outfile.txt

However, I need to do it for all files in the directory. Inserting a wildcard is not helping as it is printing headers first and then the grep output.


Solution

for file in *
do
  [ "$file" = outfile.txt ] && continue
  head -n 1 "$file"
  grep -i '...' "$file"
done > outfile.txt


Answered By - Ignacio Vazquez-Abrams
Answer Checked By - David Marino (WPSolving Volunteer)