how.wtf

Grep for contents after pattern match

· Thomas Taylor

There may be a need to grep for a specific pattern but only capture / echo the contents after the match.

grep will match on any pattern you supply; however, what if a user wants to capture the status of a particular host in the following file?

1hostname1: bad
2hostname2: good
3hostname3: good
4hostname4: bad

Get contents after grep match using sed

Using a combination of grep and sed, this can be accomplished:

1grep 'hostname1' file.txt | sed 's/^.*: //'

Evaluation:

  1. grep matches any line that contains hostname2
  2. sed replaces (s/// substitute) any character (.*) from the beginning of the line (^) until the last occurrence of the sequence : with the empty string of .

Output:

1bad

Get contents after grep match using awk

If the delimiter is known ahead of time, awk is a simpler approach.

1grep 'hostname2' file.txt | awk '{print $2}'

Evaluation:

  1. grep matches any line that contains hostname2
  2. awk prints the second field after the delimiter (which is space by default)
    1. use the -F option to switch delimiters: ex. awk -F "," for commas

Output:

1good

Get contents using awk only

awk may optionally be used by itself to extract the value.

1awk '/hostname4:/ {print $2}' file.txt

Output:

1bad

#linux  

Reply to this post by email ↪