I've got a bunch on strings which I need to find in a couple of files, for example:
string1
string2
stringn
file1.txt
file2.txt
filen.txt
Is there an (easy) way to do that in bash? I need to know, if a string was found, in which file is it.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communitySimple grep command with -e option:
grep -e "string1" -e "string2" -e "stringn" file*.txt
Or you can put all the search strings in a file called search.txt like this:
string1
string2
string3
...
...
stringN
and then run grep like this with -f
option:
grep -f search.txt file*.txt
echo -e "string1\nstring2\nstringn" | grep -f - search.txt file*.txt
Use grep to search for all the strings in one pass:
grep -E -H 'string1|string2|stringn' file1.txt file2.txt filen.txt
The -E
lets you use the pipe character(|) without escaping it. The -H
prints the filename for each match. The regular expression uses pipes to separate each string, so that grep
will try to match each one in order.
There is a variant of grep that supports this feature for large sets of strings, try
fileWithListOfSearchTargets=myFileOfSearchTargets.txt
fgrep -f ${fileWithListOfSearchTargets} file1 file2 ... filen
(The variable and filenames are meant to be self-documenting, you can use any name you like)
You have to enter all your search strings into the file.
No leading or trailing spaces unless you expect those to match in your filelist.
There is a limit to the size that most fgrep
s can process. Don't try to cram 10K lines into one file.
The best way is to use grep:
grep -H 'string to search' file1.txt file2.txt filen.txt
will search the specified files for a string, and print out the matching lines along with the filename where the match was found.
for searchString in "string1 string2 stringn"; do grep -H $searchString file1.txt file2.txt; done
However, this assumes that searchString is an easy word -- if it has symbols, spaces, you need more escaping.
Unix find command:
find . -exec grep "i want to find this string" '{}' \; -print
will search from current dir and down.
This works too:
egrep -r 'arbitrary string' *
egrep "(string1|string2|string3)" file{1..3}.txt