Greetings!
I have been tasked to create a report off files we receive from our hardware suppliers. I need to grep these files for two fields ‘Test_Version’ and ‘Model-Manufacturer’ ; for each field, I need to capture their corresponding values.
When running each statement separately, I get the results I want:
1) for ‘Test_Version’, it was straightforward:
find . -name "*.VER" -exec grep 'Test_Version=' '{}' ';' -print;
./(FILE_NAME).VER
Test_Version=2.6.3
./(FILE_NAME).VER
Test_Version=2.4.7
2) for ‘Model-Manufacturer’, , it was a bit tricky since what I need is across multiple lines. I solved this issue by using Perl Regex option -P.
find . -name "*.VER" -exec grep -P 'Model-Manufacturer:.\n.' '{}' ';' -print
./(FILE_NAME).VER
--> Model-Manufacturer:
D12-100
./(FILE_NAME).VER
--> Model-Manufacturer:
H21-100
Ideally, I would like to create a simple report that looks like this
(FILE_NAME)
Test_Version=2.6.3
Model-Manufacturer: D12-100
(FILE_NAME)
Test_Version=2.4.7
Model-Manufacturer: H21-100
My attempt to combine both greps is not working i.e nothing is found:
find . -name "*.VER" -exec grep -P 'Test_Version=.Model-Manufacturer:.\n.' '{}' ';' -print
How can I grep to search for both fields and produce the output I want?
I created a test file:
I created a copy, to replicate searching through multiple files:
Finally, I am able to generate the report you’re looking for using the following string of commands:
egrepallows for extended regular expressions, in which I’m using|as the alternation operator.The
-Aflag to(e)grep, makes it provide a line of context after each match. If your input files have unwanted content after theTest_Versionlines, you may need to include agrep -vcommand piped in betweenfindandsedto strip out the unwanted output.