Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does awk print the entire line instead of the first field?

Tags:

shell

awk

I'm trying to learn to use awk but it's not behaving how I expect. Here's my trouble:

$ echo "Hello brave new world" | awk "{print $1}"
Hello brave new world

I expected to see "Hello", as this is the first field. Why don't the spaces count as field delimiters?

like image 403
Robert Martin Avatar asked Feb 18 '12 01:02

Robert Martin


People also ask

How do I print the first column in awk?

awk to print the first column. The first column of any file can be printed by using $1 variable in awk. But if the value of the first column contains multiple words then only the first word of the first column prints. By using a specific delimiter, the first column can be printed properly.

How do I print an entire line in awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.


1 Answers

It's because Bash is interpreting $1 as referring to the first shell argument, so it replaces it with its value. Since, in your case, that parameter is unset, $1 just gets replaced with the empty string; so your AWK program is actually just {print }, which prints the whole line.

To prevent Bash from doing this, wrap your AWK program in single-quotes instead of double-quotes:

echo "Hello brave new world" | awk '{print $1}'

or

echo 'Hello brave new world' | awk '{print $1}'
like image 140
ruakh Avatar answered Oct 15 '22 17:10

ruakh