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
499 views
in Technique[技术] by (71.8m points)

csv - Ignoring embeded spaces with AWK

I'm looking for a simple way to print a specific field with awk while allowing for embedded spaces in the field.

Sample: Field1 Field2 "Field Three" Field4

I want to be able to do the equivalent to awk '{print $3}' but getting "Field Three" as a single field not two.

Update: More specifically, I need to get later fields not $3 but the space in #3 is what's messing things up. The number of spaces between the quotes in $3 is variable. I'm just wanting to be able to treat what's between quotes as a single field even if not all fields are quoted. So, ignoring the spaces as field separators if between quotes.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can do this if the double quotes are always there:

awk -F" '{print $2}'

Specifically, I am telling awk that the fields are separated by double quotes, at which point the part you want is readily available as field 2.

If you need to get at subsequent fields, you can split the remainder of the line on spaces and get a new array, say F[] of fields, like this:

awk -F" '{split($3,F," ");print $2,F[1],F[2]}' file

Field Three Field4 Field5

assuming your file looks like this:

Field1 Field2 "Field Three" Field4 Field5 Field6

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

...