10

How do you watch a command like?

awk 'NR%2==0 {printf "%s %8.0f", $1, $5}' filename.txt

Preceding this with "watch" gives this error:

awk: cmd. line:1: fatal: cannot open file `{printf' for reading (No such file or directory)

The answer to: Using the watch command with an argument that contains quotes was to escape the $ signs by replacing them with \$. But that gives me the error:

sh: -c: line 0: syntax error near unexpected token `('
                                                      sh: -c: line 0: 

I wanted to ask this in the comment to that question but didn't have enough points to make comments.

Similar questions where the answers that worked for them did not work in this case:

1) https://askubuntu.com/questions/500217/how-to-properly-quote-piped-command-for-watch (answer was again to escape $ sign).
2), 3), and 4) are listed in the comments since I cannot post more than 2 links without 10 points reputation.

2 Answers2

15

There are four approaches.

1. Place the command in double-quotes

Both the double-quotes and the dollar-signs need to be escaped:

watch "awk 'NR%2==0 {printf \"%s %8.0f\", \$1, \$5}'" filename.txt

2. Place the command in single-quotes

Inside single-quotes, neither " nor $ need to be escaped. It is, however, not possible to include single-quotes within a single-quoted string. If we need a single-quote to appear, the work-around is to end the single-quoted string and add an escaped single-quote, \'. It looks like this:

watch 'awk '\''NR%2==0 {printf "%s %8.0f", $1, $5}'\' filename.txt

3. Hybrid approach

Combining both of the above, we put the first part of the string in double-quotes and the second part in single-quotes:

watch "awk 'NR%2==0 {printf "'"%s %8.0f", $1, $5}'\' filename.txt

4. Unquoted but fully escaped

If we don't enclose the command in quotes, we will need to escape all the needed shell-active characters. That includes spaces, quotes, curly-braces, and dollar-signs:

watch awk\ \'NR%2==0 \{printf\ \"%s\ %8.0f\",\ \$1,\ \$5\}\' filename.txt
John1024
  • 17,343
3

This is an old thread but this issue will never go away. Here it is, escape the awk chars ', $ and %:

$ watch -d -n 10 'ls -ltr | grep exec_setsid_ | grep out | tail -1 | awk '\'{ print \$9 }\'' | xargs tail -25'

This command will show the last 25 lines of the newer "exec_sedsid_*.out" file that was created in the current folder!

Pronto!