Tuesday, August 6, 2019

linux - Using double quotes in awk




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?


Answer



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

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...