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: 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:
grep
matches any line that containshostname2
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:
grep
matches any line that containshostname2
awk
prints the second field after the delimiter (which is space by default)- use the
-F
option to switch delimiters: ex.awk -F ","
for commas
- use the
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