3
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.

1
  • 1
    Using cat is unnecessary: CFG=$(ssh $i "awk '{print $2}' log.txt") Commented Sep 30, 2010 at 22:16

6 Answers 6

4

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}'"`
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is so helpful! Thanks schot!
3

try

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

2 Comments

thanks, but I just edited my question again. Now backslash doesn't work. Can you please look into it again?
I'm not sure what you're trying to do there. Are you just trying to output the 2nd column of "log.txt" for each host in $LIST?
1

Make sure you're escaping the $2 from the shell - the ssh command you end up sending right now is something like this: ssh listvalue cat log.txt|awk '{print }'

Comments

1
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).

Comments

1

I was able to put awk in a double for loop

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

3 Comments

Be sure to format your code in your answer to make it look like code ```
@unmultimedio No. SO uses four spaces at the beginning of all lines within a codeblock
You're right, it's `code` for code-line and 4 spaces for code-block
0

Lose the cat. Its useless..

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.