Mussé Redi
Mussé Redi

Reputation: 945

gawk system-command ignoring backslashes

Consider a file with a list of strings,

string1
string2
...
abc\de

.

When using gawk's system command to execute a shell command , in this case printing the strings,

cat file | gawk '{system("echo " $0)}'

the last string will be formatted to abcde. $0 denotes the whole record, here this is just the one string

Is this a limitation of gawk's system command, not being able to output the gawk variables unformatted?

Upvotes: 1

Views: 78

Answers (2)

Mussé Redi
Mussé Redi

Reputation: 945

In Bash we use double backslashes to denote an actual backslash. The function of a single backslash is escaping a character. Hence the system command is not formatting at all; Bash is.

The solution for this problem is writing a function in awk to preformat backslashes to double backslahses, afterwards passing it to the system command.

Upvotes: 0

John1024
John1024

Reputation: 113924

Expanding on Mussé Redi's answer, observe that, in the following, the backslash does not print:

$ echo 'abc\de' | gawk '{system("echo " $0)}'
abcde

However, here, the backslash will print:

$ echo 'abc\de' | gawk '{system("echo \"" $0 "\"")}'
abc\de

The difference is that the latter command passes $0 to the shell with double-quotes around it. The double-quotes change how the shell processes the backslash.

The exact behavior will change from one shell to another.

To print while avoiding all the shell vagaries, a simple solution is:

$ echo 'abc\de' | gawk '{print $0}'
abc\de

Upvotes: 1

Related Questions