Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

linux - Why isn't this awk command working

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...