问题描述:

I have a file messages.txt with 100 or so lines, and I want to search inside all files of a given directory for occurrences of any of the lines in messages.txt. The search must be recursive.

It would also be nice if the search could be matched against a regex. It turns out that each line of the messages.txt is of the form foo=bar, and I'm only interested in the foos, so I need to ignore the =bar for every line. (It would be easy to overcome this by preparing a new messages.txt, but it would be nice to know if there's a feature that does that already).

My choices here are Python (because I like it) and bash scripting (because I'm trying to learn it). I could easily come up with a Python script, so if you give a solution in Python it would be appreciated if it's in a Pythonic way. However, my preference is for bash - I was hoping a mixture of sed, grep, find and cat (not necessarily all of the them) might do the trick.

Thanks

网友答案:

Simply use fgrep:

fgrep -rlf messages.txt dir

Or grep -f

grep -Frlf messages.txt dir

If you want to search for regex, don't use -F:

grep -rlf messages.txt dir

Update: If your lines messages.txt contain patterns like foo=bar, you can use cut with process substitution and cut in bash:

grep -rlf <(cut -d = -f 2- messages.txt) dir
网友答案:
grep -r -f message.txt *

should do the trick

相关阅读:
Top