How to parse Linux command output using ‘grep’, ‘awk’ and ‘print’

Let’s say you the command echo and you want to capture its output and parse it in some way. First step is to extract the piece of information from the output that you need. So, to get the word “text” from the output “some text here”, you could specify the following:

echo "some text here" | awk '{print $2}' ----> "text"

Very nice. What happens is that awk automatically splits up the output into tokens (in this case separated by spaces) and selects the 2nd token, indicated by $2, for printing.

If we want to store the extracted value for later use, we can do the following:

value = $(echo "some text here" | awk '{print $2}')

When we now print value to the screen, we again see “text”

echo $value ----> "text"

If the original command (in the above example echo) produces multi-line output, you may first need to use the grep command to find the correct line, before using awk to extract the right token.

Scroll to Top