简体   繁体   中英

Bash script using awk in for loop

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.

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}'"`

try

for i in $LIST
do
  ssh $i "cat log.txt|awk '{print \$2}'"
done

确保你从shell ssh listvalue cat log.txt|awk '{print }'$2 - 你现在最终发送的ssh命令是这样的: ssh listvalue cat log.txt|awk '{print }'

for server in $LIST
do
   ssh "$server" 'awk "{print $2}" log.txt'
done
  • Carefully watch the location of the single-quote and the double-quote .
  • Bash tries to expand variables ( words beginning with $ ) inside double-quote ( " ).
  • Single-quote ( ' ) stops Bash from looking for variables inside.
  • As user131527 and psj suggested, escaping $2 with \\ should also have worked (depending on how your Bash is configured).

Lose the cat. Its useless..

for server in $LIST
do
  ssh "$server" "awk '{print \$2}' log.txt"
don

我能够将awk放入双循环中

for i in 1 2 3 4;do for j in $\\(ls | awk -v I=$i '{print $I}'); echo $j done; done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM