Using Awk to Get Second Column

Using Awk to Get Second Column

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.

1

2 Answers

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 )
0

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 agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.