Linux grep все кроме

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"

grep exclude keyword

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 excludes multiple keywords

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.

  • –exclude-dir
    If -R is specified, it excludes directories matching the given filename pattern from the search.
  • -R, -r, –recursive
    Recursively search subdirectories listed.

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 directory

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.

Читайте также:  Увеличить размер виртуальной машины linux

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 file

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 examples

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

Источник

Как исключить в Grep

Команда Pgrep в Linux

g rep — это мощный инструмент командной строки, который используется для поиска в одном или нескольких входных файлах строк, соответствующих регулярному выражению, и записывает каждую совпадающую строку в стандартный вывод.

В этой статье мы покажем вам, как исключить одно или несколько слов, шаблонов или каталогов при поиске с помощью grep.

Исключить слова и шаблоны

Чтобы отображать только те строки, которые не соответствуют поисковому шаблону, используйте параметр -v (или —invert-match).

Например, чтобы напечатать строки, которые не содержат строку, nologinвы должны использовать:

grep -wv nologin /etc/passwd
root:x:0:0:root:/root:/bin/bash git:x:994:994:git daemon user:/:/usr/bin/git-shell andreyex:x:1000:1000:andreyex:/home/andreyex:/bin/bash

Опция -w говорит grepвернуть только те строки, где указанная строка представляет собой целое слово (заключенные символы без слов).

По умолчанию учитывается регистр grep. Это означает, что символы верхнего и нижнего регистра рассматриваются как разные. Чтобы игнорировать регистр при поиске, вызовите grep с опцией -i.

Читайте также:  Линукс перенаправление вывода ошибок

Если строка поиска содержит пробелы, вам необходимо заключить ее в одинарные или двойные кавычки.

Чтобы указать два или более шаблонов поиска, используйте опцию -e:

grep -wv -e nologin -e bash /etc/passwd

Вы можете использовать опцию -e сколько угодно раз.

Другой вариант исключения нескольких шаблонов поиска — объединение шаблонов с помощью оператора ИЛИ |.

В следующем примере печатаются строки, не содержащие строк nologin или bash:

grep -wv 'nologin\|bash' /etc/passwd

GNU grepподдерживает три синтаксиса регулярных выражений: базовый, расширенный и совместимый с Perl. По умолчанию grepинтерпретирует шаблон как базовое регулярное выражение, в котором метасимволы, например, | теряют свое особое значение, и вы должны использовать их версии с обратной косой чертой.

Если вы используете опцию расширенного регулярного выражения -E, то оператор | не следует экранировать, как показано ниже:

grep -Ewv 'nologin|bash' /etc/passwd

Вы можете указать различные возможные совпадения, которые могут быть буквальными строками или наборами выражений. В следующем примере исключаются строки games, в которых строка находится в самом начале строки:

Вывод команды может быть отфильтрован grepчерез конвейер, и только строки, соответствующие заданному шаблону, будут напечатаны на терминале.

Например, чтобы распечатать все запущенные процессы в вашей системе, кроме тех, которые выполняются от имени пользователя «root», вы можете отфильтровать вывод команды ps:

Исключить каталоги и файлы

Иногда при выполнении рекурсивного поиска с опциями -r или -R вы можете захотеть исключить определенные каталоги из результатов поиска.

Основное различие между параметрами -r или -R заключается в том, что когда grep вызывается с прописными буквами, Rон будет следовать всем символическим ссылкам.

Чтобы исключить каталог из поиска, воспользуйтесь опцией —exclude-dir. Путь к исключенному каталогу относительно каталога поиска.

Вот пример, показывающий, как искать строку andreyex во всех файлах внутри /etc, за исключением каталога /etc/pki:

grep -R --exclude-dir=pki andreyex /etc

Чтобы исключить несколько каталогов, заключите исключенные каталоги в фигурные скобки и разделите их запятыми без пробелов.

Например, чтобы найти файлы , которые содержат строку «gnu» в вашей системе Linux исключая proc, bootи sysкаталоги , которые вы бы запустить:

Читайте также:  Linux исправление ошибок жестких дисков

При использовании сопоставления с подстановочными знаками вы можете исключить файлы, базовое имя которых совпадает с GLOB, указанным в опции —exclude.

В приведенном ниже примере мы ищем строку во всех файлах в текущем рабочем каталоге, за исключением файлов andreyex, оканчивающихся на .pngи .jpg:

Заключение

Команда grepпозволяет исключить шаблоны и каталоги при поиске файлов.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

grep exclude multiple strings

I am trying to see a log file using tail -f and want to exclude all lines containing the following strings: Nopaging the limit is and keyword to remove is I am able to exclude one string like this:

tail -f admin.log|grep -v "Nopaging the limit is" 

8 Answers 8

Filtering out multiple lines with grep :

Put these lines in filename.txt to test:

grep command using -E flag with a pipe between tokens in a string:

grep -Ev 'def|jkl' filename.txt 

egrep using -v flag with pipe between tokens surrounded by parens:

egrep -v '(def|jkl)' filename.txt 

Or if stacking -e flags through grep parameters is okay (credit -> @Frizlab ):

grep -Fv -e def -e jkl filename.txt 

With the -F flag, you can use newlines as delimiters instead of pipes. This allows the use of command output as the filter more easily, e.g.: grep -vF $(pgrep myprocess)

grep -Fv -e 'Nopaging the limit is' -e 'keyword to remove is' 

-F matches by literal strings (instead of regex)

-e allows for multiple search patterns (all literal and inverted)

This is the right answer: The only one that avoids both the multiple grep -v instances and the artificial requirement of a regex (lets the multiple strings be specified cleanly in separate arguments). Just imagine constructing that regex programmatically in a script for strings that could contain anything…

Actually none of these are right answers because when passing no keywords to exclude it will exclude everything instead of nothing.

Источник

Оцените статью
Adblock
detector