Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep -f file to print in order as a file

I have a a requirement to grep patterns from a file but need them in order.

$ cat patt.grep
name1
name2

$ grep -f patt.grep myfile.log
name2:some xxxxxxxxxx
name1:some xxxxxxxxxx

I am getting the output as name2 was found first it was printed then name1 is found it is also printed. But my requirement is to get the name1 first as per the order of patt.grep file.

I am expecting the output as

name1:some xxxxxxxxxx
name2:some xxxxxxxxxx
like image 278
Sriharsha Kalluru Avatar asked Feb 20 '14 13:02

Sriharsha Kalluru


People also ask

How do I sort grep results?

To sort anything you need to use the sort command. You can use grep to identify the lines to sort, then pipe the output to sort and use the -h switch for a numeric sort with -k identifying what column to sort on.

How do I use grep to print?

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. The output shows only the lines with the exact match.

How do I grep a pattern from a file?

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'.

How do I print a line before and after grep?

To also show you the lines before your matches, you can add -B to your grep. The -B 4 tells grep to also show the 4 lines before the match. Alternatively, to show the log lines that match after the keyword, use the -A parameter. In this example, it will tell grep to also show the 2 lines after the match.


3 Answers

You can pipe patt.grep to xargs, which will pass the patterns to grep one at a time.

By default xargs appends arguments at the end of the command. But in this case, grep needs myfile.log to be the last argument. So use the -I{} option to tell xargs to replace {} with the arguments.

cat patt.grep | xargs -Ihello grep hello myfile.log
like image 181
owlman Avatar answered Oct 30 '22 23:10

owlman


Use the regexes in patt.grep one after another in order of appearance by reading line-wise:

while read ptn; do grep $ptn myfile.log; done < patt.grep
like image 27
J. Katzwinkel Avatar answered Oct 30 '22 23:10

J. Katzwinkel


i tried the same situation and easily solved using below command:

I think if your data in the same format as you represent then you can use this.

grep -f patt.grep myfile.log | sort

enter image description here

like image 36
Tajinder Avatar answered Oct 31 '22 00:10

Tajinder