模式后如何grep内容? [英] 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
用空字符串(^
)开始到最后出现的序列:
(冒号后跟空格)的任何字符(.*
) >-将第一部分替换为第二部分(空白).
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
=定界符,\
=转义的空格字符,例如-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
中的所有行,然后,对于每行,进行与上述第一个示例相同的替换,然后打印出来.
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
发送文件(< file.txt
通过stdin
将文件内容发送到左侧的命令)到awk
脚本,该脚本针对包含potato:
的每一行(<如果正则表达式/potato:/
与当前行匹配,则c28>返回true),如上所述,打印第二个字段.
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
(< file.txt
,请参见上文)发送到一个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).
这篇关于模式后如何grep内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!