简体   繁体   中英

greping two regex at the same time

How to use grep to search for two regex at the same time. Say, I am looking for "My name is" and "my bank account " in a text like:

My name is Mike. I'm 16 years old.
I have no clue how to solve my grep problem,but
if I manage to solve it, then I'll transfer 
you some money from my bank account. 

I'd like grep to return:

My name is my bank account

Is it possible to do it with just one grep call or should I write a script to do that for me?

pipe. grep expr1 file | grep expr2

for or - egrep '(expr1|expr2)' file

I'm not quite sure what you're after. The result you give doesn't seem to fit with anything grep can/will do. In particular, grep is line oriented, so if it finds a match in a line, it includes that entire line in the output. Assuming that's what you really want, you can just or the two patterns together:

grep ("My name is" | "my bank account")

Given the input above, this should produce:

My name is Mike. I'm 16 years old.
you some money from my bank account. 

Alternatively, since you haven't included any meta-characters in your patterns, you could use fgrep (or grep -F) and put your patterns in a file, one per line. For two patterns this probably doesn't make a big difference, but if you want to look for lots of patterns, it'll probably be quite a bit faster (it uses the Aho-Corasick string search to search for all the patterns at once instead of searching for them one at a time).

The other possibility would be that you're looking for a single line that includes both my name is and my bank account . That's what @djechlin's answer would do. From the input above, that would produce no output, so I doubt it's what you want, but if it is, his answer is fairly reasonable. An alternative would be a pattern like ("My name is.*my bank account" | "my bank account.*My name is") .

Yes. It is possible. I used sed. You can replace S1 and S2 with whatever you want

sed '/S1/{ s:.*:S1:;H};/S2/{ s:.*:S2:;H};${x;s:\n: :g;p};d' 

Sed is much more complex than grep, and in this case I used it to simulate grep's behaviour that you wish.

If you do not care about a trailing newline, simply use grep :

< file.txt grep -o "My name is\|my bank account" | tr '\n' ' '

If you would prefer a trailing newline, use awk :

awk -v RS="My name is|my bank account" 'RT != "" { printf "%s ", RT } END { printf "\n" }' file.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM