如何使用grep,sed和awk在找到的模式后打印下一个单词? [英] How to print the next word after a found pattern with grep,sed and awk?
本文介绍了如何使用grep,sed和awk在找到的模式后打印下一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,假设我有logfile.txt其中包含这是一个示例文本文件"
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.
推荐答案
以下是使用awk的一种方法:
Here is one way to do it with awk:
$ awk '{for(i=1;i<=NF;i++)if($i=="sample")print $(i+1)}' file
text
解释:
$ awk '{
for(i=1;i<=NF;i++) # process every word
if($i=="sample") # if word is sample
print $(i+1) # print the next
}' file
并sed:
$ sed -n 's/.* sample \([^ ]*\).*/\1/p' file
text
即. sample
之后的下一个以空格分隔的字符串
ie. after sample
next space separated string
和grep使用PCRE并保持积极的眼光:
and grep using PCRE and positive look behind:
$ grep -oP '(?<=sample )[^ ]*' file
text
请参阅前面的说明.
这篇关于如何使用grep,sed和awk在找到的模式后打印下一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文