简体   繁体   English

如何使用grep,sed和awk在找到的模式后打印下一个单词?

[英]How to print the next word after a found pattern with grep,sed and awk?

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. 我的模式是“样本”如何在logfile.txt中获取示例旁边的单词。

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 \([^ ]*\).*/\1/p' file
text

ie. 即。 after sample next space separated string sample下一个空格分隔字符串

and grep using PCRE and positive look behind: 和使用PCRE的grep和积极看待背后:

$ grep -oP '(?<=sample )[^ ]*' file
text

See the previous explanation. 请参阅前面的说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM