Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use grep and regular expressions in shell

Shulou Source: shulou.com Published: 2022-06-02 04:51:33 10月02日 Update

This article is about how to use grep and regular expressions in shell. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Match the beginning and end characters

Format: grep {^ string | string $} filename

Example: grep ^ [a Merz] tr filename;grep tr$ filename

We see that ^ [amurz] matches characters that begin with the letter amurz, and o $matches characters that end with the letter o.

2. Match the whole word

Format: grep'\ btom\ b' 2.txt

We see the whole word that matches tom.

3 、? The use of + and *

Use: grep {... |? |. *} filename

. Matching a single character can match spaces; * matches the repetition of any character or string multiple times;. + characters must appear once;.? The character appears 0 or 1 times.

Example: a >. The match of b > *. Note: grep does not support +? Metacharacters must have the-E option

We see so much in aa*, which means to match any number of a characters; there are no characters that begin with n when you directly n.+, and you have to add-E to show them; so. + and.? What's the difference? . + is all matched, and.? It just matches the character immediately after the character n.

Let's take a look at the greedy matching of Perl's regular expression-PRV c >. *; d >. *? The lazy match.

We see that the difference between them is that greedy matching matches all to the entire string, while lazy matching just matches the string tom.

4. The label of grep

Format: grep'\ (str\)\ (\)\ (\) [other]\ 1' filename

We see that after matching tom and hello, add two more characters, and then successfully match the first two lines of the string.

5. Pattern search in grep

The format 1:grep'[str]\ {2\} 'filename; searches for lines containing tom twice in the text

The format 2:grep'[str]\ {1,\} 'filename; searches for lines containing tom at least once in the text

The format 3:grep'[str]\ {1J 3} 'filename; search text contains lines containing tom for 1 to 3 times

Lines that begin with tom and appear one or three times in a row

Thank you for reading! This is the end of this article on "how to use grep and regular expressions in shell". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Characters formatting string beginning search regular expression text greed content words just letters inertia time more usefulness examples articles good Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi MySQL macOS Shulou Information Shulou Tech Info