Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

bash - Unable to separate semi-colon separated line awk

I am trying to do the following:

  1. Read a file line by line.
  2. Each line has the following structure: field1;field2;field3
  3. Use awk to separate each of these fields and then process each of these fields further

The snippet of code I have is:

while read l
do
n=`echo ${l} | awk --field-separator=";" '{print NF}'`
field1=`echo ${l} | awk --field-separator=";" '{print $1}'`
field2=`echo ${l} | awk --field-separator=";" '{print $2}'`
field3=`echo ${l} | awk --field-separator=";" '{print $3}'`
echo ${n} ${field1} ${field2} ${field3} 
done < temp 

Where temp contains only the following line:

xx;yy;zz  

The answer I get on the command line is:

1 xx;yy;zz

I am not sure I understand this output. Any explanations would be nice, given that it does work for other files. I am working on a Mac while this code uses awk within a bash script.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Why awk when you can do it in pure bash?

while IFS=';' read -r field1 field2 field3; do
    echo "Field1: $field1"
    echo "Field2: $field2"
    echo "Field3: $field3"
done < file.txt

Or if you don't know the field count:

while IFS=';' read -ra fields; do        
    echo "Number of fields: ${#fields[@]}"
    echo "Field1 ${fields[0]}"
done < file.txt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...