Site icon LinuxCommands.site

How does grep exclude directory, file, keyword in Linux/unix

In linux/unix, “grep exclude” allows us to find what we need to find more accurately.

The grep command supports multiple exclusion methods, including grep to exclude directory, grep to exclude file, grep to exclude binary files, and grep to exclude keywords.

Today we will focus on the above several “grep exclude” usage examples.

Grep exclude keywords

Grep exclude keywords or word“, this is the function I use most frequently in the linux grep command, it can well block the interference of big data to me.

The grep command excludes keywords. We can use the grep -v option, which can which can invert the match.

grep -v syntax

# grep excludes a single keyword
➜  grep -v "keyword" file

# grep excludes multiple keywords
➜  grep -v "keyword1" file | grep -v "keyword2" | ...

grep -v examples

In the following example, we will use grep to search for keywords and exclude specific keyword.

➜  ~ grep -i 'use' test.log | grep -v "option"

In the following example, we will use a pipeline with grep to exclude multiple keywords.

➜  ~ grep -i 'use' test.log | grep -v "option" | grep -v "find"

Grep exclude directory

Grep exclude directories, we can use the grep –exclude-dir option, which needs to be used with the grep -R option.

Grep –exclude-dir excludes directories matching the given file name pattern from the search.

grep –exclude-dir syntax

# grep exclude a directory
➜  grep --exclude-dir "directory" -R "keyword" .

# grep exclude multiple directories
➜  grep --exclude-dir "directory1" --exclude-dir "directory2" -R "keyword" .

grep –exclude-dir examples

In the following example, we use grep –exclude-dir to exclude one or more directories.

➜  grep --exclude-dir "test" -R "grep" .
...

➜  grep --exclude-dir "test" --exclude-dir "backup" -R "grep" .
...

Grep exclude file

Grep exclude file, as with excluding directories, we can use the grep –exclude option, which will exclude files matching the given file name pattern from the search.

grep — exclude syntax

# grep exclude a file
➜  grep --exclude "file" "keyword" files

# grep exclude multiple files
➜  grep --exclude "file1" --exclude "file1" "keyword" files

grep — exclude examples

In the following example, we will use the grep –exclude option to exclude one or more files during pattern search.

➜ grep --exclude "test.log" "grep" *.log
...

➜ grep --exclude "test.log" --exclude "m.log" "grep" *.log
...

Grep exclude binary files

When we use the grep command pattern search, we often find some binary files, these are not what we need, so we need to exclude these binary files.

Grep exclude binary files, we can use grep -I option, it can ignore binary files when searching.

grep -I syntax

➜ grep -I "keyword" .

grep -I examples

In the following example, we will use the grep -I option to ignore the binary file search content.

➜ grep -RI "grep" .

Exit mobile version