如何在模式后搜索内容? [英] How to grep for contents after pattern?
问题描述
给定一个文件,例如:
potato: 1234
apple: 5678
potato: 5432
grape: 4567
banana: 5432
sushi: 56789
我想对所有以 potato:
开头的行进行 grep,但只传递 potato:
后面的数字.所以在上面的例子中,输出将是:
I'd like to grep for all lines that start with potato:
but only pipe the numbers that follow potato:
. So in the above example, the output would be:
1234
5432
我该怎么做?
推荐答案
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
(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).
这篇关于如何在模式后搜索内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!