Skip to content
Advertisement

Why doesn’t grep -lv work?

I want to print out the name of a file if and only if it does not contain the string foo. However, if file contains foo and I run this

grep -lv 'foo' file

file is outputted. Why does this happen and what can I do to work around it?

Advertisement

Answer

-v means to match any line that doesn’t match the pattern. So -lv means to list any file that contains any line that doesn’t match the pattern. That’s not the same as a file where none of the lines match the pattern.

Use the -L option to list all files that don’t have any match for the pattern.

grep -L 'foo' file

-L, --files-without-match
Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.

Don’t use -v with this. -L already inverts which files are listed, and -v inverts the way lines are matched, so -Lv is the same as -l.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement