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
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.
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.
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'.
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.
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With