bash 如何使用 grep、sed 和 awk 打印找到的模式后的下一个单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48606867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print the next word after a found pattern with grep,sed and awk?
提问by James Brown
for example, suppose I have logfile.txt which contains "Here is a sample text file"
例如,假设我有 logfile.txt,其中包含“这是一个示例文本文件”
My pattern is "sample" How can I get the word next to sample in my logfile.txt.
我的模式是“sample” 我怎样才能在我的 logfile.txt 中获得 sample 旁边的单词。
回答by James Brown
Here is one way to do it with awk:
这是使用 awk 执行此操作的一种方法:
$ awk '{for(i=1;i<=NF;i++)if($i=="sample")print $(i+1)}' file
text
Explained:
解释:
$ awk '{
for(i=1;i<=NF;i++) # process every word
if($i=="sample") # if word is sample
print $(i+1) # print the next
}' file
and sed:
和 sed:
$ sed -n 's/.* sample \([^ ]*\).*//p' file
text
ie. after sample
next space separated string
IE。后sample
一个空格隔开的字符串
and grep using PCRE and positive look behind:
和 grep 使用 PCRE 和积极的后面看:
$ grep -oP '(?<=sample )[^ ]*' file
text
See the previous explanation.
参见前面的解释。