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

北城余情 提交于 2021-02-18 22:26:28

问题


for example, suppose I have logfile.txt which contains "Here is a sample text file"

My pattern is "sample" How can I get the word next to sample in my logfile.txt.


回答1:


Here is one way to do it with 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 -n 's/.* sample \([^ ]*\).*/\1/p' file
text

ie. after sample next space separated string

and grep using PCRE and positive look behind:

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

See the previous explanation.



来源:https://stackoverflow.com/questions/48606867/how-to-print-the-next-word-after-a-found-pattern-with-grep-sed-and-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!