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?
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.
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.
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}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With