I have a file, each line of which is a list of comma separated values. For example,
1, a, b, c, d, e 2, x, y, z
Now I would like to convert it in bash as follows:
1 a 1 b 1 c 1 d 1 e 2 x 2 y 2 z
How to do it with a shell (bash) script?
awk -F, '{for(i=2;i<=NF;i++)print $1,$i}' temp
tested below:
> cat temp
1, a, b, c, d, e
2, x, y, z
> awk -F, '{for(i=2;i<=NF;i++)print $1,$i}' temp
1 a
1 b
1 c
1 d
1 e
2 x
2 y
2 z
You can split the line into tokens and put them in an array. The first element of the array will be having the number, in your case it is 1 or 2 and so on. Something like this may be :
while read line
do
arrIN=(${line//,/ })
## make a loop and echo them
## arrIN[0] will have the initial number
done < $file
# $file is the input file you are reading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With