I want to search
all files include text "hello
" but exclude
the result contains "test
".
Here is the example files:
mkdir -p /tmp/test
cd /tmp/test
echo "foo hello" > foo.txt
echo "bar world" > bar.txt
echo "test hello" >> bar.txt
echo "world hello" >> bar.txt
Here is the search for "hello":
# find /tmp/test -type f -name '*' -exec grep -H -i "hello" {} ;
/tmp/test/bar.txt:test hello
/tmp/test/bar.txt:world hello
/tmp/test/foo.txt:foo hello
Now I want to exclude "test" from the above search output:
# find /tmp/test -type f -name '*' -exec grep -H -i "hello" {} ; | grep -v "test"
...Nothing here...
Try other pattern:
# find /tmp/test -type f -name '*' -exec grep -H -i "hello" -v "test" {} ;
grep: test: No such file or directory
/tmp/test/bar.txt:bar world
grep: test: No such file or directory
Here is the expected output:
# find /tmp/test -type f -name '*' -exec grep [commands argumensts here] {} ;
/tmp/test/bar.txt:world hello
/tmp/test/foo.txt:foo hello
How to do this search
and exclude
for find in files?
3
Answers
The issue is that you have
test
in the file path.You can match for things after the
:
but that will only work if you do not have:
in the text of the file.Example:
You can use awk which can parse file contents very quickly. The following sample script
gives the output
BUT … note that the 3 reject lines go to stderr. if you redirect stdout to a file, you will only have the list of good files in that list.
Use awk instead of grep: