问题
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