Why isn't this awk command working

2019-09-19 10:13发布

问题:

So the question is:

Display all of the lines in the file showing only the quantity and product name, in that order, using awk. Product name is the first field and quantity is the second field. The data file is "inventory"

The contents to inventory:

Strawberry Jam,300,4

Raspberry Jam,1216,7

Blueberry Jam,96,195

Strawberry Compote,49,621

Raspberry Compote,1937,624

Blueberry Compote,200,625

Frozen Strawberries,130,1941

Straw Hats,16,2047

My command was

awk '$2 $1' inventory

That should work right? I also tried like

awk '{print $2 $1}' inventory
awk '$2, $1' inventory

and a lot of variations of that, but none works! Can anyone help figure out why?

回答1:

That is a csv (comma seperated values) file so the field separator needs to be specified as , using the -F option.

$ awk -F, '{print $2,$1}' inventory

300 Strawberry Jam
1216 Raspberry Jam
96 Blueberry Jam
49 Strawberry Compote
1937 Raspberry Compote
200 Blueberry Compote
130 Frozen Strawberries
16 Straw Hats


回答2:

Here we go:

awk 'BEGIN{FS=OFS=","} {print $2, $1}' inventory