Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script using awk in for loop

Tags:

bash

awk

for i in $LIST
do
  CFG=`ssh $i "cat log.txt|awk '{print $2}'"`
  for j in $CFG
  do
    echo $j
  done
done

Say I want to print 2nd field in the log file on a couple remote host. In above script, print $2 doesn't work. How can I fix this? Thanks.

like image 546
Stan Avatar asked Jul 24 '26 07:07

Stan


1 Answers

Depending on the number of shell expansions and type of quoting multiple backslash escapes are needed:

awk '{ print $2 }' log.txt # none
ssh $server "awk '{ print \$2 }' log.txt" # one
CFG=`ssh $server "awk '{ print \\$2 }' log.txt"` # two
CFG=$(ssh $server "awk '{ print \$2 }' log.txt") # one (!) 

As a trick you can put a space between the dollar sign and the two to prevent all $ expansion. Awk will still glue it together:

  CFG=`ssh $i "cat log.txt|awk '{print $ 2}'"`
like image 71
schot Avatar answered Jul 28 '26 17:07

schot