I have three strings that I search for within a file. To find the lines with either one of them, I use
grep 'string1\|string2\|string3' file
I want to print out only the matched strings within each line, using the -o
flag. But in this case if two of the strings are present in the line, only one of them shows up. Is there a way to get something like string1
and/or string2
etc. without having to list 6 cases with and and or using this answer.
Note that I am using OS X Yosemite.
Expected output:
string1
string1 string2
string3
string1 string3
string3
etc.
Answer
You can try to print the line numbers, The records which are repeated
will not have the line numbers. Then just join the line with post processing.
grep -Eon 'string1|string2|string3' txt
1:string1
2:string2
string3
3:string3
4:string1
string2
In above case 2:string2
and string3
can be joined to form string2 string3
Complete command on Mac OS
grep -Eon 'string1|string2|string3' txt | tr '\n' ' '
| sed -E 's/ [0-9]:/:/g' | tr ':' '\n'
the last tr
& sed
command can be replaced with single sed
command. but somehow new line character not working on Mac sed.
The output will be similar to this
string1
string2 string3
string3
string1 string2 string3
No comments:
Post a Comment