One linux command a day - grep

grep (abbreviated from Globally search a Regular Expression and Print) is a powerful text search tool that searches text using specific pattern matches (including regular expressions) and outputs matching lines by default.

Syntax Usage: grep [OPTION]... PATTERNS [FILE]...

example:

This is a simple file with some simple content.

Output the content of the line where hello is located

grep 'hello' testsimplegrep.txt

Output lines with hello regardless of case

grep -i 'hello' testsimplegrep.txt

Pattern selection and interpretation (optional pattern and interpretation)

-E sums -e:

-e can only pass one parameter, if you need to pass multiple parameters, you need to -e

For example: grep -e 'HELLO' -e 'test' testssimplegrep.txt

If you use -E, multiple parameters can be separated by |

Syntax: grep -E 'HELLO|test|linux' testsimplegrep.txt | means or (or)

Use of grep -F:

View the contents of the file as follows

grep -F means to treat the grep command as using fixed strings (fixed strings) instead of regular expressions to match patterns. In this mode, grep searches for strict text matches, rather than using special characters in regular expressions. This is usually faster than regular expressions.

When using the -F option, you need to pay attention that the pattern string cannot contain metacharacters of regular expressions, such as parentheses, asterisks, etc. grep will match the pattern string as normal text.

Let's take a look at the results of using -E: grep -E 'test|rege' testsimplegrep.txt

再来看下-F 的结果: grep -F 'test|rege' testsimplegrep.txt

-i:忽略大小写

grep -i 'linux' testsimplegrep.txt, 看到大写LINUX 和小写linux 都查出来了

-n:显示关键字所在的行

grep -n 'linux' testsimplegrep.txt

-c: 显示关键字显示的次数

grep -c 'linux' testsimplegrep.txt

Context control:

-B, --before-context=NUM print NUM lines of leading context

-A, --after-context=NUM print NUM lines of trailing context

-C, --context=NUM print NUM lines of output context

用于在给定文件或文件集中搜索模式或文本字符串,并显示包含该模式的行以及指定数量的匹配行之前的行数。

grep 命令的 -B 选项表示“before(之前)”,并指定在匹配行之前要显示多少行。

grep -i 'unix-type' testsimplegrep.txt -B 1

当B = 1时,查询结果后多显示1行,当B =2 时,查询结果后多显示俩行。

-A (after)同理,显示结果后,往后显示n行;

-C 是从查询到的结果,上下文显示n行

grep -n -i 'unix-type' testsimplegrep.txt -C 1: 上线文显示1行

grep -n -i 'unix-type' testsimplegrep.txt -C 2 上线文显示2行

Guess you like

Origin blog.csdn.net/qq_20714801/article/details/129355670