Linux split a column into two different columns in

2019-02-25 02:36发布

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

5条回答
三岁会撩人
2楼-- · 2019-02-25 03:05

Here's a nice crazy shell pipeline that actually does what the OP wants :!

#% cat t
11
22
13
,,
aa
bb
cc
,,
ww
kk
ll
,,

Then

#% pr -t -3 -l 4 -s' ' t | sed '$d'
11 aa ww
22 bb kk
13 cc ll

I'm sure there's better commands without resorting to code.

EDIT Thanks to @user000001 for the heads-up on my error making me revisit my solution.

查看更多
The star\"
3楼-- · 2019-02-25 03:05

with awk

awk 'BEGIN {RS=",,\n"; FS="[\n]"}{ }{a=a$1" ";b=b$2" ";c=c$3" ";} END{print a"\n"b"\n"c}' temp.txt

Output

11 aa ww
22 bb kk
13 cc ll
查看更多
Anthone
4楼-- · 2019-02-25 03:06

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; #resed 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
查看更多
姐就是有狂的资本
5楼-- · 2019-02-25 03:22
perl -lne 'if(/,,/){$.=0}$a{$.}=$a{$.}." ".$_ if($.!=0);END{foreach (sort keys %a){print $a{$_}}}'

Tested below:

> cat temp
11
22
13
,,
aa
bb
cc
,,
ww
kk
ll
,,
> perl -lne 'if(/,,/){$.=0}$a{$.}=$a{$.}." ".$_ if($.!=0);END{foreach (sort keys %a){print $a{$_}}}' temp
 11 aa ww
 22 bb kk
 13 cc ll
> 
查看更多
女痞
6楼-- · 2019-02-25 03:26

This might work for you:

pr -tT3 -s\  file | sed \$d
查看更多
登录 后发表回答