I can not seem to get the awk command to get the second column of data.

Bash Code:

filter_data=$(awk "{if(/$filter:/) print $2}" < scanresults_temp.txt)

printf  "$filter_data \n"

The $filter variable is either the value of Download or Upload that gets passed into the shell script. So awk uses the term Download or Upload to search for the proper row.

The file contents are:

Testing download speed................................................................................
Download: 51.13 Mbit/s
Testing upload speed................................................................................................
Upload: 57.38 Mbit/s

I am trying to get just the numbers and not anything else, ex, 51.13 and 57.38.

  • 2
    Why save it to variable if you're printing it right away ? Just use awk's printf – Sergiy Kolodyazhnyy Sep 12 at 21:31
up vote 12 down vote accepted

You need to use single quotes for the awk program body so awk's variables are not expanded by the shell. Here's how you should pass a shell variable into awk:

filter_data=$( awk -v re="$filter:" '$0 ~ re {print $2}' scanresults_temp.txt )
  • Perfect, thank you. – Vlad Sep 12 at 20:13

Alternative way is to let shell put variable into awks environment via proceeding assignment ( temporary ):

re=$filter  awk  '$0 ~ ENVIRON["re"] {print $2}'  input.txt

Note that variable quoting isn't necessary when performing assignments in shell

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.