rusia.inc
rusia.inc

Reputation: 931

Weird awk behaviour , $1 is printed but $0 is not?

This is printed fine ls | xargs -I var sh -c 'echo var | awk "{print $1}"'

while this is not ls | xargs -I var sh -c 'echo var | awk "{print $0}"'

Obviously this is not my use case and is just to reproduce the problem.

So while $0 stands for complete line, it is weird for $0 to not print while $1 gets printed.

Reference OS - Ubuntu 14.04

Upvotes: 3

Views: 1772

Answers (2)

StevenWernerCS
StevenWernerCS

Reputation: 868

For others landing here: If your syntax was perfect but you are potentially using windows files, remember the \r will effectively overwrite your text and make it seem like $0 is blank....

First run dos2unix <file>, then try your awk.

Note: removing \r with sed or tr isn't enough

Upvotes: 1

anubhava
anubhava

Reputation: 786359

When you use:

ls | xargs -I var sh -c 'echo var | awk "{print $0}"'

That has $0 in double quotes hence $0 gets expanded by shell which is in this case has value sh without quotes. awk treats it as a variable and prints blank.

To make it work escape the $:

ls | xargs -I var sh -c 'echo var | awk "{print \$0}"'

Why $1 works:

ls | xargs -I var sh -c 'echo var | awk "{print $1}"'

$1 also gets expanded by shell and it is empty. Hence awk just executes an empty print which is equivalent of print $0 and you get filename in output.

However it is not a good idea to use awk command in double quotes and parsing ls output is error prone.

Upvotes: 7

Related Questions