Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert CSV file in bash?

Tags:

bash

shell

csv

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?

like image 923
Michael Avatar asked Dec 05 '25 08:12

Michael


2 Answers

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
like image 83
Vijay Avatar answered Dec 07 '25 20:12

Vijay


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
like image 35
gaganbm Avatar answered Dec 07 '25 22:12

gaganbm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!