Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux split a column into two different columns in a same CSV file [closed]

Hi I have a csv file with below entries

11
22
13
,,
aa
bb
cc
,,
ww
kk
ll
,,

Please suggest me a linux command or script which can split this colomun into 3 columns in the same file like below

11  aa  ww
22  bb  kk
13  cc  ll
like image 779
Ujjawal Khare Avatar asked Feb 11 '26 21:02

Ujjawal Khare


1 Answers

You can do it with awk.

Create a file named script.awk, with the following contents:

BEGIN {
   line = 0; #Initialize at zero
}
/,,/ { #every time we hit the delimiter
   line = 0; #reset line to zero 
}
!/,,/{ #otherwise
   a[line] = a[line]" "$0; # Add the new input line to the output line
   line++; # increase the counter by one 
}
END {
   for (i in a )
      print a[i] # print the output
}

Run file like this:

awk -f test.awk < datafile 

Output:

$ cat datafile
11
22
13
,,
aa
bb
cc
,,
ww
kk
ll
,,
$ awk -f script.awk < datafile 
 11 aa ww
 22 bb kk
 13 cc ll

Or if you just want a one-liner, do this:

awk 'BEGIN{line=0;}/,,/{line=0;}!/,,/{a[line++]=a[line]" "$0;}END{for (i in a ) print a[i]}' datafile 

EDIT:

This will add commas between the fields:

awk 'BEGIN{line=0;}/,,/{line=0;}!/,,/{a[line++]=a[line]?a[line]","$0:$0;}END{for (i in a ) print a[i]}' datafile
                                                              # ^ This is the part that I changed
like image 72
user000001 Avatar answered Feb 13 '26 13:02

user000001