If you’re looking for a specific line in a file that doesn’t match, grep can be used to print it. To use grep, type the following command: grep -v ‘^[a-zA-Z0-9]*$’ text.txt
grep is a command line search utility for Linux that will print out lines in files that match a pattern or regular expression. It’s also useful to invert matches, which will filter out all lines in a file that contain the given string.
Negative Matching With grep
To use negative matching in grep, you should execute the command with the -v or –invert-match flags. This will print only the lines that don’t match the pattern given.
Keep in mind though that since grep isn’t matching anything, there’s no way to use the -o flag to print “only the matches,” since nothing has technically matched. grep is able to match multiple times per line, but in this case, it will not matter if there are multiple matches. Any single match will cause grep to omit the line.
This works with regular expressions (regex) as well and will print any line that files to match the regex.
While you can write regular expressions that do negative matching, it’s generally easier to invert the match this way.
Alternatively, if you prefer using awk, you can use the exclamation modifier to invert regex.
Negative Matching Filenames
The lowercase -l flag will cause grep to print the filenames containing matches instead of the actual matched content. This can be useful when scanning a list of files, but similarly, it’s also useful to invert this sometimes.
The inverse of -l is the uppercase variant, -L, which does the opposite:
Make sure you don’t use the -v flag with -L to invert the match before printing the files without the match, or you will run into a “double opposites” situation where the match is inverted twice and does not have the intended effect.