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

5 linux bash awk grep sed

例如,假设我有logfile.txt,其中包含"这是一个示例文本文件"

我的模式是"样本"如何在logfile.txt中获取示例旁边的单词.

Jam*_*own 12

以下是使用awk执行此操作的一种方法:

$ awk '{for(i=1;i<=NF;i++)if($i=="sample")print $(i+1)}' file
text
Run Code Online (Sandbox Code Playgroud)

和sed:

$ awk '{
    for(i=1;i<=NF;i++)        # process every word
        if($i=="sample")      # if word is sample
            print $(i+1)      # print the next
}' file
Run Code Online (Sandbox Code Playgroud)

和使用PCRE的grep和积极看待背后:

$ sed -n 's/.* sample \([^ ]*\).*/\1/p' file
text
Run Code Online (Sandbox Code Playgroud)