0

I am trying to read a remote file using ssh with gawk command, but I am failing with quotes issue.

ssh <HOST> 'gawk -v RS='"' 'NR % 2 == 0 { gsub(/\n/, "") } { printf("%s%s", $0, RT) }' "<File name>" | wc -l'

I appreciate if anyone help to resolve this.

Sanjay Chintha
  • 326
  • 1
  • 4
  • 21
  • You can't nest single quotes inside a single-quoted string. Use `"..."` (escaping dollar signs, double quotes, and backslashes as necessary), or use `$'...'` (escaping single quotes and backslashes as necessary). Or, punt on the issue by copying a script to the remote host and executing it. – chepner Aug 04 '21 at 18:01
  • I am bit confused. can you please be specific o mention in command @chepner. – Sanjay Chintha Aug 04 '21 at 18:05
  • https://www.google.com/search?q=unix+ssh+command+quotes – Ed Morton Aug 04 '21 at 18:50

1 Answers1

0

'gawk -v RS='"' '... is not a string that contains RS='"'. It's equivalent to

gawk -v RS="'  '...

The shell doesn't know that you want the entire string between the first and last ' should be treated literally; it reads from the first ' until the next ', then continues parsing.

Further, there's no way to quote a single quote inside '...', as the backslash itself is taken literally. '\'' is not a single '; it's ' and \.

If you are using bash or a shell with a similar extension, you can use ANSI-style quoting. You'll have to ensure that all literal ' and '\ are escaped.

# Should be correct, not not tested
ssh <HOST> $'gawk -v RS=\'"\' \'NR % 2 == 0 { gsub(/\\n/, "") } { printf("%s%s", $0, RT) }\' "<File name>" | wc -l'

Or you can use "..." as the outer quotes, and ensure all literal $ and " are escaped (as well as any \ that would otherwise be treated as an escape character).

# Should be correct, not not tested
ssh <HOST> "gawk -v RS='\"' 'NR % 2 == 0 { gsub(/\n/, \"\") } { printf(\"%s%s\", \$0, RT) }" "<File name>" | wc -l'

My preference would be to avoid the problem by putting your code in a script

#!/bin/sh
gawk -v RS='"' 'NR % 2 == 0 { gsub(/\n/, "") } { printf("%s%s", $0, RT) }' "<File name>" | wc -l

copying that to the remote host

scp <HOST>:\~/myscript

and executing it

ssh <HOST> 'sh myscript'
chepner
  • 497,756
  • 71
  • 530
  • 681