How to invert a grep expression on Linux?

LinuxOperating SystemOpen Source

In order to be able to invert a grep expression on Linux command line, we must first understand what a grep command is and how to use it on Linux.

The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search.

Normally, the pattern that we are trying to search in the file is referred to as the regular expression.

Syntax

grep [options] pattern [files]

While there are plenty of different options available to us, some of the most used are −

-c : It lists only a count of the lines that match a pattern
-h : displays the matched lines only.
-i : Ignores, case for matching
-l : prints filenames only
-n : Display the matched lines and their line numbers.
-v : It prints out all the lines that do not match the pattern

Now, let’s consider a case where we want to find a particular pattern in all the files in a particular directory, say dir1.

Syntax

grep -rni "word" *

In the above command replace the “word” placeholder with

For that we make use of the command shown below −

grep -rni "func main()" *

The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well.

Output

main.go:120:func main() {}

In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −

grep -s "func main()" *

In the above command we made use of the -s flag which will help us to not get a warning for each subdirectory that is present inside the directory where we are running the command.

Output

main.go:120:func main() {}

Inverting Grep Expression

In order to invert a grep expression, we just need to make use of the -v flag along with the grep command.

Consider the command shown below that will print all the files that are ending with .go extension.

Command

ls -R |grep -E *\go

Output

immukul@192 src % ls -R |grep -E *\go
grep: learning-go: Is a directory
grep: livego: Is a directory
grep: todd-go: Is a directory

Command

Now to invert the grep command, type the following command in your terminal.

ls -R |grep -v -E *\go

Output

grep: learning-go: Is a directory
grep: livego: Is a directory
main.go:package main
main.go:
main.go:import (
main.go: "bytes"
main.go: "fmt"
main.go:
.
.
raja
Published on 30-Jul-2021 08:46:09
Advertisements