Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

AWK is printing all columns

Writer Matthew Barrera

I want to isolate the second column.

If I do:

echo "1 2 3" | awk "{ print $2 }"

the result is:

1 2 3

The expected result is:

2

I've tried with -F' ' option, but the result is the same.

What am I doing wrong?

3 Answers

You need single quotes:

echo "1 2 3" | awk '{ print $2 }'

will return 2

1

What am I doing wrong?

echo "1 2 3" | awk "{ print $2 }"

The correct command is

echo "1 2 3" | awk '{ print $2 }'

Or

echo "1 2 3" | awk "{ print \$2 }"

Example:

$ echo "1 2 3" | awk '{ print $2 }'
2
$ echo "1 2 3" | awk "{ print \$2 }"
2
6

A correct approach has been already given in two other answers:

echo "1 2 3" | awk '{print $2}'

The "why", though, was lacking, so I am adding it.

echo "1 2 3" | awk "{print $2}"

fails because shells perform parameter expansion on $2. I.e., it retrieves the value of that variable, just as a=6;echo "$a" prints 6 in the command-line. From the POSIX shell manual,

Enclosing characters in double-quotes ( "" ) shall preserve the literal value of all characters within the double-quotes, with the exception of the characters backquote (`), dollar-sign ($), and backslash (\).

Unless your shell was started with arguments (highly unlikely scenario), $2 expands to the null string and awk never sees $2, just {print }, thus printing the whole 1 2 3 string.

Bear in mind that it is false to say that the awk program must be enclosed in single-quotes. Awk just needs to get its bytes and could not care less about what steps the shell takes to deliver them. So, these are also correct:

echo "X Y Z" | awk "{print \$2}"
echo "X Y Z" | awk \{print\ \$2\}

Yikes! I said it was correct, not clean.

Conclusion: Surround the awk program in single-quotes whenever possible.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy