Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include header in the 'grep' result

Tags:

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.

like image 489
Curious Avatar asked Oct 16 '12 17:10

Curious


People also ask

Can I use * in grep command?

Grep can identify the text lines in it and decide further to apply different actions which include recursive function or inverse the search and display the line number as output etc. Special characters are the regular expressions used in commands to perform several actions like #, %, *, &, $, @, etc.

What does '- Q do in grep?

grep defines success as matching 1 or more lines. Failure includes matching zero lines, or some other error that prevented matching from taking place in the first place. -q is used when you don't care about which lines matched, only that some lines matched.

What does * do with grep?

To Show Lines That Exactly Match a Search String The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option.

How do I use grep to search output?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.


1 Answers

The following means you only need type the command once (rather than using && and typing it twice), it's also quite simple to understand.

some-command | { head -1; grep some-stuff; } 

e.g.

ps -ef | { head -1; grep python; } 

UPDATE: This only seems to work for ps, sorry, but I guess this is usually what people want this for.

If you want this to work for an arbitrary command, it seems you must write a mini script, e.g.:

#!/bin/bash  first_line=true  while read -r line; do     if [ "${first_line}" = "true" ]; then         echo "$line"         first_line=false     fi     echo "$line" | grep $* done 

Which I've named hgrep.sh. Then you can use like this:

ps -ef | ./hgrep.sh -i chrome 

The nice thing about this approach is that we are using grep so all the flags work exactly the same.

like image 190
samthebest Avatar answered Oct 07 '22 02:10

samthebest