Monday, March 4, 2019

regex - Using grep to print one of the listed strings but print all of them if more than one exists



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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...