简体   繁体   中英

Escape awk command in ssh

I have the following command;

su user1 -c "ssh user1@192.168.1.2 awk '$5\==1{print\$3}' filename.log" | uniq -c

Running the command gives the error:

awk: ==1{print
awk: ^ syntax error
awk: cmd. line:1: ==1{print
awk: cmd. line:1:          ^ unexpected newline or end of string

I have tried several escaping methods with no luck. Any advice will be deeply appreciated. Thanks.

I would go for this:

su user1 -c "ssh user1@192.168.1.2 \"awk '\\\$5==1{print \\\$3}' filename.log\"" | uniq -c
                                   ^^                                    ^^

Basically, first of all you need to imagine how to execute the command if you are user1 :

ssh user1@192.168.1.2 "awk '\\\$5==1{print \\\$3}' filename.log"

and then you introduce it into the su user1 ... escaping the quotes.

Escaping the right way is quite tricky. You could write like this:

su user1 -c 'ssh user1@192.168.1.2 awk \"\\\$5 == 1 {print \\\$3}\" filename.log' | uniq -c

or like this:

su user1 -c "ssh user1@192.168.1.2 awk \'\\\$5 == 1 {print \\\$3}\' filename.log" | uniq -c

That is, you need to escape the quotes and the $ signs within the quoted string. Since the $ signs always need to be escaped, you need to double-escape it in this case, that's why the \\\\\\ .

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