JOHN LEE
JOHN LEE

Reputation: 11

Unix separate string line with delimiter

I have a few line of string in txt file like this:

input.txt-->

abc;def;ghi jklm;mno pqr;
abcde;fgh;ijk lmno;pqrs tuv;

my code is this. It did not work with space. Please help.

awk -F";" '{print $1,$2,$3,$4}' input.txt | while read var1    
var2 var3 var4 
Do
 echo 'var1 = ' $var1
 echo 'var2 = ' $var2
 echo 'var3 = ' $var3
 echo 'var4 = ' $var4
Done

desired output-->

var1 = abc
var2 = def
var3 = ghi jklm
var4 = mno pqr

var1 =abcde
var2 =fgh
var3 =ijk lmno
var4 =pqrs tuv

Upvotes: 0

Views: 10257

Answers (1)

fedorqui
fedorqui

Reputation: 289725

This can make it:

while IFS=';' read -r val1 val2 val3 val4
do
  echo "val1 = $val1"
  echo "val2 = $val2"
  echo "val3 = $val3"
  echo "val4 = $val4"
done < input.txt

The basic aspect to take into consideration is IFS=";" which defines the Input Field Separator. With read -r val1 .. val4 we indicate which variables will be defined.

It can be easier with awk:

$ awk -F";" '{for (i=1; i<NF; i++) {print "val"i,"=",$i}}' input.txt

It basically defines ; as field separator with the -F ";". Then loops through all these fields with the for i and prints them. NF indicates the number of fields and The loop is up to NF-1 so that the last empty one is not shown. Thanks JS웃 for the tip :)

Test

$ while IFS=';' read -r val1 val2 val3 val4; do echo "val1 = $val1"; echo "val2 = $val2"; echo "val3 = $val3"; echo "val4 = $val4"; echo; done < a
val1 = abc
val2 = def
val3 = ghi jklm
val4 = mno pqr

val1 = abcde
val2 = fgh
val3 = ijk lmno
val4 = pqrs tuv

awk version:

$ awk -F";" '{for (i=1; i<NF; i++) {print "val"i,"=",$i}}' a
val1 = abc
val2 = def
val3 = ghi jklm
val4 = mno pqr
val1 = abcde
val2 = fgh
val3 = ijk lmno
val4 = pqrs tuv

Upvotes: 4

Related Questions