linux grep regex examples

Grep regex matches the search content according to the specified rule pattern, which can help us find the content we need precisely.

Let’s take a look at how to use grep regular pattern matching.

This is the content of the test file required for the demonstration.

➜  ~ cat test.txt
1:11111
1:22222
3:22222
2:33333
4:ddddd

Grep regex filter

Match content starting with a specific character

In the following example, we will use grep to regularly match the content in the test file that starts with the number “1”.

➜  ~ grep -E "^1" test.txt
1:11111
1:22222
➜  ~ grep "^1" test.txt
1:11111
1:22222

Match content that contains the specified string

In the following example, we will use grep to match the content of the specified string in the test file. For example, match content that contains “22”.

➜  ~ grep -E "22" test.txt
1:22222
3:22222
➜  ~ grep "22" test.txt
1:22222
3:22222

Match content ending with the specified character

In the following example, we will use grep to regularly match the content in the test file that ends with the specified character. For example, match content ending in the number “3”.

➜  ~ grep -E "3$" test.txt
2:33333

Match and filter content that starts with the number “1” or “2”.

➜  ~ grep -E "^[12]" test.txt
1:11111
1:22222
2:33333

Match filters content that contains multiple strings

For example, matches content that contains “1:2” or “2:2”.

➜  ~ grep -E "1:2|2:3" test.txt
1:22222
2:33333

Match content that starts with a specific string and ends with a special string.

For example, match content that starts with 1 and ends with 2.

➜  ~ grep -E "^1.*2$" test.txt
1:22222

Match content with a specific content format. For example, match content that contains “3..2”.

➜  ~ grep -E "3..2" test.txt
3:22222

start with a number

➜  ~ grep -E "^[0-9]" test.txt
1:11111
1:22222
3:22222
2:33333
4:ddddd

grep match blank line

➜  ~ grep -n "^$" test.txt

Add a Comment

Your email address will not be published.