- Регулярные выражения в Grep (Regex)
- Регулярное выражение Grep
- Буквальные совпадения
- Якорь
- Соответствующий одиночный символ
- Выражения в скобках
- Квантификаторы
- Чередование
- Группировка
- Специальные выражения обратной косой черты
- Выводы
- Regular expressions in grep ( regex ) with examples
- Regular Expressions in grep
- Three types of regex
- grep Regular Expressions Examples
- How to match single characters
- How to match only dot (.)
- Anchors
- How to match sets of character using grep
- How negates matching in sets
- Wildcards
- Using Grep & Regular Expressions to Search for Text Patterns in Linux
- Introduction
- Prerequisites
- Basic Usage
- Common Options
- Regular Expressions
- Literal Matches
- Anchor Matches
- Matching Any Character
- Bracket Expressions
- Repeat Pattern Zero or More Times
- Escaping Meta-Characters
- Extended Regular Expressions
- Grouping
- Alternation
- Quantifiers
- Specifying Match Repetition
- Conclusion
Регулярные выражения в Grep (Regex)
grep — одна из самых полезных и мощных команд Linux для обработки текста. grep ищет в одном или нескольких входных файлах строки, соответствующие регулярному выражению, и записывает каждую совпадающую строку в стандартный вывод.
В этой статье мы собираемся изучить основы использования регулярных выражений в GNU-версии grep , которая по умолчанию доступна в большинстве операционных систем Linux.
Регулярное выражение Grep
Регулярное выражение или регулярное выражение — это шаблон, который соответствует набору строк. Шаблон состоит из операторов, конструирует буквальные символы и метасимволы, которые имеют особое значение. GNU grep поддерживает три синтаксиса регулярных выражений: базовый, расширенный и Perl-совместимый.
В своей простейшей форме, когда тип регулярного выражения не указан, grep интерпретирует шаблоны поиска как базовые регулярные выражения. Чтобы интерпретировать шаблон как расширенное регулярное выражение, используйте параметр -E (или —extended-regexp ).
Как правило, вы всегда должны заключать регулярное выражение в одинарные кавычки, чтобы избежать интерпретации и расширения метасимволов оболочкой.
Буквальные совпадения
Наиболее простое использование команды grep — поиск буквального символа или серии символов в файле. Например, чтобы отобразить все строки, содержащие строку «bash» в /etc/passwd , вы должны выполнить следующую команду:
Результат должен выглядеть примерно так:
В этом примере строка «bash» представляет собой базовое регулярное выражение, состоящее из четырех буквальных символов. Это указывает grep искать строку, в которой сразу после grep «b» идут «a», «s» и «h».
По умолчанию команда grep чувствительна к регистру. Это означает, что символы верхнего и нижнего регистра рассматриваются как разные.
Чтобы игнорировать регистр при поиске, используйте параметр -i (или —ignore-case ).
Важно отметить, что grep ищет шаблон поиска как строку, а не слово. Итак, если вы искали «gnu», grep также напечатает строки, в которых «gnu» встроено в слова большего размера, например, «cygnus» или «magnum».
Если в строке поиска есть пробелы, вам нужно заключить ее в одинарные или двойные кавычки:
Якорь
Якоря — это метасимволы, которые позволяют указать, где в строке должно быть найдено совпадение.
Символ ^ (каретка) соответствует пустой строке в начале строки. В следующем примере строка «linux» будет соответствовать только в том случае, если она встречается в самом начале строки.
Символ $ (доллар) соответствует пустой строке в начале строки. Чтобы найти строку, заканчивающуюся строкой «linux», вы должны использовать:
Вы также можете создать регулярное выражение, используя оба якоря. Например, чтобы найти строки, содержащие только «linux», выполните:
Еще один полезный пример — шаблон ^$ , который соответствует всем пустым строкам.
Соответствующий одиночный символ
Файл . (точка) символ — это метасимвол, который соответствует любому одиночному символу. Например, чтобы сопоставить все, что начинается с «кан», затем имеет два символа и заканчивается строкой «ру», вы должны использовать следующий шаблон:
Выражения в скобках
Выражения в квадратных скобках позволяют сопоставить группу символов, заключив их в квадратные скобки [] . Например, найдите строки, содержащие «принять» или «акцент», вы можете использовать следующее выражение:
Если первый символ внутри скобок — это курсор ^ , то он соответствует любому одиночному символу, не заключенному в скобки. Следующий шаблон будет соответствовать любой комбинации строк, начинающихся с «co», за которыми следует любая буква, кроме «l», за которой следует «la», например «coca», «cobalt» и т. Д., Но не будет соответствовать строкам, содержащим «cola». ”:
Вместо того, чтобы помещать символы по одному, вы можете указать диапазон символов внутри скобок. Выражение диапазона создается путем указания первого и последнего символов диапазона, разделенных дефисом. Например, [aa] эквивалентно [abcde] а 3 эквивалентно [123] .
Следующее выражение соответствует каждой строке, начинающейся с заглавной буквы:
grep также поддерживает предопределенные классы символов, заключенные в скобки. В следующей таблице показаны некоторые из наиболее распространенных классов символов:
Квантификатор | Классы персонажей |
---|---|
[:alnum:] | Буквенно-цифровые символы. |
[:alpha:] | Буквенные символы. |
[:blank:] | Пробел и табуляция. |
[:digit:] | Цифры. |
[:lower:] | Строчные буквы. |
[:upper:] | Заглавные буквы. |
Полный список всех классов персонажей можно найти в руководстве по Grep .
Квантификаторы
Квантификаторы позволяют указать количество вхождений элементов, которые должны присутствовать, чтобы совпадение произошло. В следующей таблице показаны квантификаторы, поддерживаемые GNU grep :
Квантификатор | Описание |
---|---|
* | Сопоставьте предыдущий элемент ноль или более раз. |
? | Соответствует предыдущему элементу ноль или один раз. |
+ | Сопоставьте предыдущий элемент один или несколько раз. |
Сравните предыдущий элемент ровно n раз. | |
Сопоставьте предыдущий элемент не менее n раз. | |
Соответствовать предыдущему элементу не более m раз. | |
Сопоставьте предыдущий элемент от n до m раз. |
Символ * (звездочка) соответствует предыдущему элементу ноль или более раз. Следующее будет соответствовать «right», «sright», «ssright» и так далее:
Ниже представлен более сложный шаблон, который соответствует всем строкам, которые начинаются с заглавной буквы и заканчиваются точкой или запятой. Регулярное выражение .* Соответствует любому количеству любых символов:
? (знак вопроса) символ делает предыдущий элемент необязательным и может соответствовать только один раз. Следующие будут соответствовать как «ярким», так и «правильным». ? Символ экранирован обратной косой чертой, потому что мы используем базовые регулярные выражения:
Вот то же регулярное выражение с использованием расширенного регулярного выражения:
Символ + (плюс) соответствует предыдущему элементу один или несколько раз. Следующее будет соответствовать «sright» и «ssright», но не «right»:
Фигурные скобки <> позволяют указать точное число, верхнюю или нижнюю границу или диапазон вхождений, которые должны произойти, чтобы совпадение произошло.
Следующее соответствует всем целым числам, содержащим от 3 до 9 цифр:
Чередование
Термин «чередование» представляет собой простое «ИЛИ». Оператор чередования | (pipe) позволяет вам указать различные возможные совпадения, которые могут быть буквальными строками или наборами выражений. Этот оператор имеет самый низкий приоритет среди всех операторов регулярных выражений.
В приведенном ниже примере мы ищем все вхождения слов fatal , error и critical в файле ошибок журнала Nginx :
Если вы используете расширенное регулярное выражение, то оператор | не следует экранировать, как показано ниже:
Группировка
Группировка — это функция регулярных выражений, которая позволяет группировать шаблоны вместе и ссылаться на них как на один элемент. Группы создаются с помощью круглых скобок () .
При использовании основных регулярных выражений скобки должны быть экранированы обратной косой чертой ( ).
Следующий пример соответствует как «бесстрашный», так и «меньший». ? квантификатор делает группу (fear) необязательной:
Специальные выражения обратной косой черты
GNU grep включает несколько метасимволов, которые состоят из обратной косой черты, за которой следует обычный символ. В следующей таблице показаны некоторые из наиболее распространенных специальных выражений обратной косой черты:
Выражение | Описание |
---|---|
b | Сопоставьте границу слова. |
Соответствует пустой строке в начале слова. | |
> | Соответствует пустой строке в конце слова. |
w | Подберите слово. |
s | Подберите пробел. |
Следующий шаблон будет соответствовать отдельным словам «abject» и «object». Он не будет соответствовать словам, если вложен в слова большего размера:
Выводы
Регулярные выражения используются в текстовых редакторах, языках программирования и инструментах командной строки, таких как grep , sed и awk . Знание того, как создавать регулярные выражения, может быть очень полезным при поиске текстовых файлов, написании сценариев или фильтрации вывода команд.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Источник
Regular expressions in grep ( regex ) with examples
Regular Expressions in grep
Regular Expressions is nothing but a pattern to match for each input line. A pattern is a sequence of characters. Following all are examples of pattern:
^w1
w1|w2
[^ ] foo
bar
4
Three types of regex
The grep understands three different types of regular expression syntax as follows:
grep Regular Expressions Examples
Search for ‘vivek’ in /etc/passswd
grep ‘vivek’ /etc/passwd
Sample outputs:
Search vivek in any case (i.e. case insensitive search)
grep -i -w ‘vivek’ /etc/passwd
Search vivek or raj in any case
grep -E -i -w ‘vivek|raj’ /etc/passwd
The PATTERN in last example, used as an extended regular expression. The following will match word Linux or UNIX in any case:
egrep -i ‘^(linux|unix)’ filename
How to match single characters
The . character (period, or dot) matches any one character. Consider the following demo.txt file:
$ cat demo.txt
Sample outputs:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Let us find all filenames starting with purchase:
grep ‘purchase’ demo.txt
Next I need to find all filenames starting with purchase and followed by another character:
grep ‘purchase.db’ demo.txt
Our final example find all filenames starting with purchase but ending with db:
grep ‘purchase..db’ demo.txt
How to match only dot (.)
A dot (.) has a special meaning in regex, i.e. match any character. But, what if you need to match dot (.) only? I want to tell my grep command that I want actual dot (.) character and not the regex special meaning of the . (dot) character. You can escape the dot (.) by preceding it with a \ (backslash):
grep ‘purchase..’ demo.txt
grep ‘purchase.\.’ demo.txt
Anchors
You can use ^ and $ to force a regex to match only at the start or end of a line, respectively. The following example displays lines starting with the vivek only:
grep ^vivek /etc/passwd
Sample outputs:
You can display only lines starting with the word vivek only i.e. do not display vivekgite, vivekg etc:
grep -w ^vivek /etc/passwd
Find lines ending with word foo:
grep ‘foo$’ filename
Match line only containing foo:
grep ‘^foo$’ filename
You can search for blank lines with the following examples:
grep ‘^$’ filename
Matching Sets of Characters
How to match sets of character using grep
The dot (.) matches any single character. You can match specific characters and character ranges using [..] syntax. Say you want to Match both ‘Vivek’ or ‘vivek’:
grep ‘[vV]ivek’ filename
OR
grep ‘[vV][iI][Vv][Ee][kK]’ filename
Let us match digits and upper and lower case characters. For example, try to math words such as vivek1, Vivek2 and so on:
grep -w ‘[vV]ivek6’ filename
In this example match two numeric digits. In other words match foo11, foo12, foo22 and so on, enter:
grep ‘foo45’ filename
You are not limited to digits, you can match at least one letter:
grep ‘[A-Za-z]’ filename
Display all the lines containing either a “w” or “n” character:
grep [wn] filename
Within a bracket expression, the name of a character class enclosed in “[:” and “:]” stands for the list of all characters belonging to that class. Standard character class names are:
- [[:alnum:]] – Alphanumeric characters.
- [[:alpha:]] – Alphabetic characters
- [[:blank:]] – Blank characters: space and tab.
- [[:digit:]] – Digits: ‘0 1 2 3 4 5 6 7 8 9’.
- [[:lower:]] – Lower-case letters: ‘a b c d e f g h i j k l m n o p q r s t u v w x y z’.
- [[:space:]] – Space characters: tab, newline, vertical tab, form feed, carriage return, and space.
- [[:upper:]] – Upper-case letters: ‘A B C D E F G H I J K L M N O P Q R S T U V W X Y Z’.
In this example match all upper case letters:
grep ‘[:upper:]’ filename
How negates matching in sets
The ^ negates all ranges in a set:
grep ‘[vV]ivek[^0-9]’ test
Using grep regular expressions to search for text patterns
Wildcards
You can use the “.” for a single character match. In this example match all 3 character word starting with “b” and ending in “t”:
Источник
Using Grep & Regular Expressions to Search for Text Patterns in Linux
Last Validated on September 25, 2021 Originally Published on July 22, 2013
Introduction
The grep command is one of the most useful commands in a Linux terminal environment. The name grep stands for “global regular expression print”. This means that you can use grep to check whether the input it receives matches a specified pattern. This seemingly trivial program is extremely powerful; its ability to sort input based on complex rules makes it a popular link in many command chains.
In this tutorial, you will explore the grep command’s options, and then you’ll dive into using regular expressions to do more advanced searching.
Prerequisites
To follow along with this guide, you will need access to a computer running a Linux-based operating system. This can either be a virtual private server which you’ve connected to with SSH or your local machine. Note that this tutorial was validated using a Linux server running Ubuntu 20.04, but the examples given should work on a computer running any version of any Linux distribution.
If you plan to use a remote server to follow this guide, we encourage you to first complete our Initial Server Setup guide. Doing so will set you up with a secure server environment — including a non-root user with sudo privileges and a firewall configured with UFW — which you can use to build your Linux skills.
As an alternative, we encourage you to use an interactive terminal embedded on this page to experiment with the sample commands in this tutorial. Click the following Launch an Interactive Terminal! button to open a terminal window and begin working with a Linux (Ubuntu) environment.
Basic Usage
In this tutorial, you’ll use grep to search the GNU General Public License version 3 for various words and phrases.
If you’re on an Ubuntu system, you can find the file in the /usr/share/common-licenses folder. Copy it to your home directory:
If you’re on another system, use the curl command to download a copy:
You’ll also use the BSD license file in this tutorial. On Linux, you can copy that to your home directory with the following command:
If you’re on another system, create the file with the following command:
Now that you have the files, you can start working with grep .
In the most basic form, you use grep to match literal patterns within a text file. This means that if you pass grep a word to search for, it will print out every line in the file containing that word.
Execute the following command to use grep to search for every line that contains the word GNU :
The first argument, GNU , is the pattern you’re searching for, while the second argument, GPL-3 , is the input file you wish to search.
The resulting output will be every line containing the pattern text:
On some systems, the pattern you searched for will be highlighted in the output.
Common Options
By default, grep will search for the exact specified pattern within the input file and return the lines it finds. You can make this behavior more useful though by adding some optional flags to grep .
If you want grep to ignore the “case” of your search parameter and search for both upper- and lower-case variations, you can specify the -i or —ignore-case option.
Search for each instance of the word license (with upper, lower, or mixed cases) in the same file as before with the following command:
The results contain: LICENSE , license , and License :
If there was an instance with LiCeNsE , that would have been returned as well.
If you want to find all lines that do not contain a specified pattern, you can use the -v or —invert-match option.
Search for every line that does not contain the word the in the BSD license with the following command:
You’ll receive this output:
Since you did not specify the “ignore case” option, the last two items were returned as not having the word the .
It is often useful to know the line number that the matches occur on. You can do this by using the -n or —line-number option. Re-run the previous example with this flag added:
This will return the following text:
Now you can reference the line number if you want to make changes to every line that does not contain the . This is especially handy when working with source code.
Regular Expressions
In the introduction, you learned that grep stands for “global regular expression print”. A “regular expression” is a text string that describes a particular search pattern.
Different applications and programming languages implement regular expressions slightly differently. In this tutorial you will only be exploring a small subset of the way that grep describes its patterns.
Literal Matches
In the previous examples in this tutorial, when you searched for the words GNU and the , you were actually searching for basic regular expressions which matched the exact string of characters GNU and the . Patterns that exactly specify the characters to be matched are called “literals” because they match the pattern literally, character-for-character.
It is helpful to think of these as matching a string of characters rather than matching a word. This will become a more important distinction as you learn more complex patterns.
All alphabetical and numerical characters (as well as certain other characters) are matched literally unless modified by other expression mechanisms.
Anchor Matches
Anchors are special characters that specify where in the line a match must occur to be valid.
For instance, using anchors, you can specify that you only want to know about the lines that match GNU at the very beginning of the line. To do this, you could use the ^ anchor before the literal string.
Run the following command to search the GPL-3 file and find lines where GNU occurs at the very beginning of a line:
This command will return the following two lines:
Similarly, you use the $ anchor at the end of a pattern to indicate that the match will only be valid if it occurs at the very end of a line.
This command will match every line ending with the word and in the GPL-3 file:
You’ll receive this output:
Matching Any Character
The period character (.) is used in regular expressions to mean that any single character can exist at the specified location.
For example, to match anything in the GPL-3 file that has two characters and then the string cept , you would use the following pattern:
This command returns the following output:
This output has instances of both accept and except and variations of the two words. The pattern would also have matched z2cept if that was found as well.
Bracket Expressions
By placing a group of characters within brackets ( \[ and \] ), you can specify that the character at that position can be any one character found within the bracket group.
For example, to find the lines that contain too or two , you would specify those variations succinctly by using the following pattern:
The output shows that both variations exist in the file:
Bracket notation gives you some interesting options. You can have the pattern match anything except the characters within a bracket by beginning the list of characters within the brackets with a ^ character.
This example is like the pattern .ode , but will not match the pattern code :
Here’s the output you’ll receive:
Notice that in the second line returned, there is, in fact, the word code . This is not a failure of the regular expression or grep. Rather, this line was returned because earlier in the line, the pattern mode , found within the word model , was found. The line was returned because there was an instance that matched the pattern.
Another helpful feature of brackets is that you can specify a range of characters instead of individually typing every available character.
This means that if you want to find every line that begins with a capital letter, you can use the following pattern:
Here’s the output this expression returns:
Due to some legacy sorting issues, it is often more accurate to use POSIX character classes instead of character ranges like you just used.
To discuss every POSIX character class would be beyond the scope of this guide, but an example that would accomplish the same procedure as the previous example uses the \[:upper:\] character class within a bracket selector:
The output will be the same as before.
Repeat Pattern Zero or More Times
Finally, one of the most commonly used meta-characters is the asterisk, or * , which means “repeat the previous character or expression zero or more times”.
To find each line in the GPL-3 file that contains an opening and closing parenthesis, with only letters and single spaces in between, use the following expression:
You’ll get the following output:
So far you’ve used periods, asterisks, and other characters in your expressions, but sometimes you need to search for those characters specifically.
Escaping Meta-Characters
There are times where you’ll need to search for a literal period or a literal opening bracket, especially when working with source code or configuration files. Because these characters have special meaning in regular expressions, you need to “escape” these characters to tell grep that you do not wish to use their special meaning in this case.
You escape characters by using the backslash character ( \ ) in front of the character that would normally have a special meaning.
For instance, to find any line that begins with a capital letter and ends with a period, use the following expression which escapes the ending period so that it represents a literal period instead of the usual “any character” meaning:
This is the output you’ll see:
Now let’s look at other regular expression options.
Extended Regular Expressions
The grep command supports a more extensive regular expression language by using the -E flag or by calling the egrep command instead of grep .
These options open up the capabilities of “extended regular expressions”. Extended regular expressions include all of the basic meta-characters, along with additional meta-characters to express more complex matches.
Grouping
One of the most useful abilities that extended regular expressions open up is the ability to group expressions together to manipulate or reference as one unit.
To group expressions together, wrap them in parentheses. If you would like to use parentheses without using extended regular expressions, you can escape them with the backslash to enable this functionality. This means that the following three expressions are functionally equivalent:
Alternation
Similar to how bracket expressions can specify different possible choices for single character matches, alternation allows you to specify alternative matches for strings or expression sets.
To indicate alternation, use the pipe character | . These are often used within parenthetical grouping to specify that one of two or more possibilities should be considered a match.
The following will find either GPL or General Public License in the text:
The output looks like this:
Alternation can select between more than two choices by adding additional choices within the selection group separated by additional pipe ( | ) characters.
Quantifiers
Like the * meta-character that matched the previous character or character set zero or more times, there are other meta-characters available in extended regular expressions that specify the number of occurrences.
To match a character zero or one times, you can use the ? character. This makes character or character sets that came before optional, in essence.
The following matches copyright and right by putting copy in an optional group:
You’ll receive this output:
The + character matches an expression one or more times. This is almost like the * meta-character, but with the + character, the expression must match at least once.
The following expression matches the string free plus one or more characters that are not white space characters:
You’ll see this output:
Specifying Match Repetition
To specify the number of times that a match is repeated, use the brace characters ( < and >). These characters let you specify an exact number, a range, or an upper or lower bounds to the amount of times an expression can match.
Use the following expression to find all of the lines in the GPL-3 file that contain triple-vowels:
Each line returned has a word with three vowels:
To match any words that have between 16 and 20 characters, use the following expression:
Here’s this command’s output:
Only lines containing words within that length are displayed.
Conclusion
grep is useful in finding patterns within files or within the file system hierarchy, so it’s worth spending time getting comfortable with its options and syntax.
Regular expressions are even more versatile, and can be used with many popular programs. For instance, many text editors implement regular expressions for searching and replacing text.
Furthermore, most modern programming languages use regular expressions to perform procedures on specific pieces of data. Once you understand regular expressions, you’ll be able to transfer that knowledge to many common computer-related tasks, from performing advanced searches in your text editor to validating user input.
Источник