Robert Martin
Robert Martin

Reputation: 17157

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

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?

Upvotes: 24

Views: 25676

Answers (4)

user2928048
user2928048

Reputation: 4118

You can use $0 for full line.

$ cat <<EOF | head -1 | sed "s/\t/\n/g" | awk 'BEGIN { cont=0} { print ++cont " " $0}'
> First Name    His/Her Phone   Electronic mail address Acquaintance or Friend
Amelia  555-5553        [email protected]    F
Anthony 555-3412        [email protected]   A
Becky   555-7685        [email protected]      A
EOF
1 First Name
2 His/Her Phone
3 Electronic mail address
4 Acquaintance or Friend

Data comes from https://www.gnu.org/software/gawk/manual/gawk.html#Sample-Data-Files but here is tab separated.

See also https://www.gnu.org/software/gawk/manual/gawk.html#Very-Simple

Upvotes: 0

Azedin
Azedin

Reputation: 41

To print the entire line, run this shell-command:

echo "Hi, this is my first answer on stackoverflow" | awk '{ print $0 }'

output:

Hi, this is my first answer on stackoverflow

Upvotes: 3

jim mcnamara
jim mcnamara

Reputation: 16379

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

Use single quotes around the awk program, otherwise $1 gets translated as the shell variable $1

Upvotes: 7

ruakh
ruakh

Reputation: 183241

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}'

Upvotes: 31

Related Questions