Grep for contents after pattern match
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: badGet contents after grep match using sed
Using a combination of grep and sed, this can be accomplished:
1grep 'hostname1' file.txt | sed 's/^.*: //'Evaluation:
grepmatches any line that containshostname2sedreplaces (s///substitute) any character (.*) from the beginning of the line (^) until the last occurrence of the sequence:with the empty string of.
Output:
1badGet 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:
grepmatches any line that containshostname2awkprints the second field after the delimiter (which is space by default)- use the
-Foption to switch delimiters: ex.awk -F ","for commas
- use the
Output:
1goodGet contents using awk only
awk may optionally be used by itself to extract the value.
1awk '/hostname4:/ {print $2}' file.txtOutput:
1bad