且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在模式后搜索内容?

更新时间:2023-09-01 18:13:16

grep 'potato:' file.txt | sed 's/^.*: //'

grep 查找任何行包含字符串 potato:,然后,对于每一行,sed 从行的开头替换(s/// - 替换)任何字符 (.*)(^) 直到最后一次出现序列 :(冒号后跟空格)和空字符串 (s/...//- 将第一部分替换为空的第二部分).

grep looks for any line that contains the string potato:, then, for each of these lines, sed replaces (s/// - substitute) any character (.*) from the beginning of the line (^) until the last occurrence of the sequence : (colon followed by space) with the empty string (s/...// - substitute the first part with the second part, which is empty).

grep 'potato:' file.txt | cut -d   -f2

对于包含 potato: 的每一行,cut 会将行分割成多个由空格分隔的字段 (-d - d = delimiter, = 转义空格字符,类似 -d" " 也可以)并打印每行的第二个字段(-f2).

For each line that contains potato:, cut will split the line into multiple fields delimited by space (-d - d = delimiter, = escaped space character, something like -d" " would have also worked) and print the second field of each such line (-f2).

grep 'potato:' file.txt | awk '{print $2}'

对于包含 potato: 的每一行,awk 将打印第二个字段 (print $2),默认情况下用空格分隔.

For each line that contains potato:, awk will print the second field (print $2) which is delimited by default by spaces.

grep 'potato:' file.txt | perl -e 'for(<>){s/^.*: //;print}'

所有包含 potato: 的行都被发送到内联 (-e) Perl 脚本,它采用 stdin中的所有行code>,然后,对于每一行,做与上面第一个例子相同的替换,然后打印出来.

All lines that contain potato: are sent to an inline (-e) Perl script that takes all lines from stdin, then, for each of these lines, does the same substitution as in the first example above, then prints it.

awk '{if(/potato:/) print $2}' < file.txt

文件通过stdin发送(通过stdin发送文件内容到左边的命令) 到 awk 脚本,对于包含 potato: (if(/potato:/) 的每一行,如果正则表达式 /potato:/ 匹配当前行),打印第二个字段,如上所述.

The file is sent via stdin (< file.txt sends the contents of the file via stdin to the command on the left) to an awk script that, for each line that contains potato: (if(/potato:/) returns true if the regular expression /potato:/ matches the current line), prints the second field, as described above.

perl -e 'for(<>){/potato:/ && s/^.*: // && print}' < file.txt

文件通过 stdin(,见上文)发送到一个 Perl 脚本,其工作方式与上述类似,但这次它也确保每一行都包含字符串 potato:(/potato:/ 是一个正则表达式,如果当前行包含 potato:,并且, 如果是 (&&),则继续应用上述正则表达式并打印结果).

The file is sent via stdin (< file.txt, see above) to a Perl script that works similarly to the one above, but this time it also makes sure each line contains the string potato: (/potato:/ is a regular expression that matches if the current line contains potato:, and, if it does (&&), then proceeds to apply the regular expression described above and prints the result).