字符串模式搜索

use*_*789 -4 grep

我是 linux 新手。我想成为系统管理员。我参加了亚马逊的面试。他们让我写一个 cmd 来查找文件中以 's' 开头并以 'a' 结尾的字符串。我知道我们必须使用grep,但不知道实际情况。除此之外,他们还询问了 grep 是如何工作的。任何人都可以简要回答这个问题。

提前致谢

Avi*_*Raj 8

试试这个带有-P(Perl-regex) 选项的GNU grep 命令,

 grep -oP '\bs.*a\b' file
Run Code Online (Sandbox Code Playgroud)

解释:

\b    # Matches the word boundary(ie, match between a word character and a non word character)
s     # Starting character would be a literal s.
.*    # Matches any character zero or more times.
a     # Matches a literal a.
\b    # Matches the word boundary(ie, match between a word character and a non word character)
Run Code Online (Sandbox Code Playgroud)


Bab*_*ton 8

grep 搜索命名输入文件(或标准输入,如果没有命名文件,或者如果给定单个连字符减号 (-) 作为文件名)中包含与给定 PATTERN 匹配的行。默认情况下,grep 打印匹配的行

Grep 命令

Grep 及其选项

-v  =   non-matching lines
-c  =   count of matching  lines
-i  =   Ignore  case
-r  =   Read all  files  under  each  directory
-l  =   list the file which contain the searching keyword
 ^      =       Search the Starting word of a file
.$      =       Search the end word of a file
^$      =       Search the empty lines in a file
Run Code Online (Sandbox Code Playgroud)

查找文件中与特定关键字匹配的所有行。

grep sysadmin /etc/passwd
Run Code Online (Sandbox Code Playgroud)

用数字显示

grep -nv nologin /etc/passwd
Run Code Online (Sandbox Code Playgroud)

避免关键字并搜索其他

grep -v sysadmin /etc/passwd
Run Code Online (Sandbox Code Playgroud)

计算与我们正在搜索的关键字匹配的行数

grep -c sysadmin /etc/passwd
Run Code Online (Sandbox Code Playgroud)

通过忽略大小写来搜索文本

grep -i sysadmin /etc/passwd
Run Code Online (Sandbox Code Playgroud)

在所有文件/home及其子目录中搜索与特定模式匹配的文本并打印匹配的行

grep -ri sysadmin /home/
Run Code Online (Sandbox Code Playgroud)

在所有文件/home及其子目录中搜索与特定模式匹配的文本并列出包含它的文件

grep -ril sysadmin /home/
Run Code Online (Sandbox Code Playgroud)

搜索多个 IP 中提到的特定 IP。在-F保证了.比赛的文字.字符,如果没有它,他们会匹配任何字符。

grep -F "192.168.1.10" /var/log/syslog
Run Code Online (Sandbox Code Playgroud)

搜索以 Feb

grep ^Feb /var/log/syslog
Run Code Online (Sandbox Code Playgroud)

搜索以 queue

grep queue$ /var/log/mail.log
Run Code Online (Sandbox Code Playgroud)

计算文件中的空行(不计算包含空格的行)

grep -c ^$ /var/log/mail.log
Run Code Online (Sandbox Code Playgroud)

在目录及其子目录的所有文件中搜索字符串

grep -r "root" .
Run Code Online (Sandbox Code Playgroud)