Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using double quotes in awk [duplicate]

Tags:

linux

shell

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?

like image 469
michael Avatar asked Oct 23 '17 04:10

michael


1 Answers

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
like image 96
the_storyteller Avatar answered Oct 16 '22 08:10

the_storyteller