Prev: read multiple fields separated by : and fields separated by , in loop stored in $var
Next: Set a variable if unset or null previously
From: Ben Bacarisse on 13 Mar 2010 10:40 Chimu <echimu(a)gmail.com> writes: > On Mar 13, 7:09 pm, Ben Bacarisse <ben.use...(a)bsb.me.uk> wrote: >> Chimu <ech...(a)gmail.com> writes: >> > I got data in $x separated by :, <snip> >> > x="tab1,c,1,3,db1:tab2,d,21,13,db45:tab12,t,11,16,db4" >> >> > output >> > Data feed: tab1 c 1 3 db1 >> > Data feed: tab2 d 21 13 db45 >> > Data feed: ab12 t 11 16 db4 <snip> >> There a lots of ways to do this, but the one that is closest to your >> original is probably: >> >> echo "$x:" | while read -r -d: field >> do >> IFS=, read -r a b c d rest <<<"$field" >> echo "Data feed: $a $b $c $d" Your output suggests that you want: IFS=, read -r a b c d e <<<"$field" echo "Data feed: $a $b $c $d $e" I.e.e that all 5 sub-fields are important to you. I missed that 1st time round. >> done <snip> > I actually come with something, but your solution seems nice too and > it never use to IFS. Here is what I did > -- > IFS=: read -r field <<<$x > for f in $field > do > IFS=, read -r a b c d <<<"$f" > echo "Data feed: $a $b $c $d" > done It's good to come up with your own solutions and a 'for' is good way to do it. However... you'll get odd results if $x contains any spaces because $field has word-splitting applied. If you think this though, you'll see that your read is redundant: you want word-splitting, and you can apply it directly to $x: IFS=: for f in $x do IFS=, read -r a b c d <<<"$f" echo "Data feed: $a $b $c $d" done is better and does suffer from the dangers of embedded spaces. Also, to match you desired output you need to read five (not four) variables in the inner read. -- Ben. |