Prev: read multiple fields separated by : and fields separated by , in loop stored in $var
Next: read multiple fields separated by : and fields separated by , in loop stored in $var
From: Chimu on 13 Mar 2010 09:21 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 :, further each field has 4 values and i > > want get those. So i come with IFS and read code > > Input > > 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 > > > my code so far > > ~~~~~~~~~~ > > while IFS=: read -r field > > do > > while IFS=, read -r a b c d > > do > > echo "Data feed: $a $b $c $d" > > done <<<"$field" > > #IFS=: > > done <<<$x > > ~~~~~~~~~~ > > > so far it is not working and i'm not able to pull data. i don't wanna > > use external tool just bash builtin and IFS. any thoughts on how to > > fix this? are you allowed to use multiple IFS? btw, I'm using bash 3.x > > on Debian Linux server. > > read will read a line and you have only one line of input so there is > nothing to loop over in the outer loop. The other problem you are > seeing is that 'field' and 'd' both get set to the remaining words and > separators which is not what you want. Also, the inner loop is not > really serving any purpose. > > 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" > done > > The -d flag causes the while/read loop to see multiple "lines". The > echo adds a terminating separator so that the last "line" is seen. > The rest variable in the inner read collects anything left over after > the parts you want. > > -- > Ben. Wow. 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 -- Guess i need to read "bash read builtin" man page as I wasn't aware of -d switch. May I know why you prefixed : for $x ? Thanks a lot for quick response. |