6

This command will print a.

echo "line1 a b c" | awk '{ print $2 }'

If I change single quotes to double quotes, like this, it will print whole line.

echo "line1 a b c" | awk "{ print $2 }"

Why? I know I should use single quotes, but why is the whole line printed if I use double quotes?

learningbee
  • 333
  • 1
  • 5
  • 11
michael
  • 397
  • 4
  • 12
  • 1
    With double quotes, the shell expands `$2` to the second positional parameter, which might very well be empty, and awk only sees `print`. – Benjamin W. Oct 23 '17 at 04:20
  • @BenjaminW. Agree with your answer, but don't think it is duplicate. – michael Oct 23 '17 at 04:34
  • 1
    I can't see how it *isn't* duplicative. An answer to how single quotes and double quotes are different in bash answers how they're different when using bash to call `awk`, because the sole difference is the shell's behavior; `awk` has no way of telling the difference between `awk '{ print }'` and `awk "{ print $2 }"` with bash having an empty `$2`. – Charles Duffy Oct 23 '17 at 15:45

1 Answers1

11

If the awk command is single quoted, the $2 is not interpreted by the shell, but is instead passed as the literal string $2 to awk. awk will then print the second space delimited token in the input string, which in this case is a.

echo "line1 a b c" | awk '{ print $2 }' # prints the second space-delimited token
> a

If the awk command is double quoted, the $2 is interpreted by the shell. Because $2 is empty (in this case), the empty string is substituted. awk sees a command which looks like awk "{ print }", which is an instruction to print everything.

echo "line1 a b c" | awk '{ print }' # prints all input
> line1 a b c

It is also possible to use double qotes, and escape the $, which will cause the $ to not be interpreted by the shell, and instead the $2 string will be passed to awk.

echo "line1 a b c" | awk "{ print \$2 }" # prints the second space-delimited token
> a
the_storyteller
  • 2,335
  • 1
  • 26
  • 37