Linux的在同一个CSV文件分割成列的两个不同的列 [英] Linux split a column into two different columns in a same CSV file

查看:976
本文介绍了Linux的在同一个CSV文件分割成列的两个不同的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有下面的条目CSV文件

  11
22
13
,,
AA
BB
CC
,,
WW
KK

,,

请给我建议Linux命令或脚本,可以此colomun在同一文件中像下面

分成3列

  11 AA WW
22 BB KK
13毫升LL


解决方案

您可以用 AWK 做到这一点。

创建一个名为 script.awk ,包含以下内容:

BEGIN {
   行= 0; #Initialize为零
}
/ ,, / {#every时间我们打的分隔符
   行= 0; #resed线到零
}
!/,,/{ #除此以外
   一个[线] = A [行]$ 0; #新的输入行添加到输出线
   行++; #增加由一个计数器
}
结束 {
   对(在ⅰ)
      打印[I]#打印输出
}

运行文件是这样的:

 的awk -f test.awk<数据文件

输出:

$猫数据文件
11
22
13
,,
AA
BB
CC
,,
WW
KK

,,
$ AWK -f script.awk<数据文件
 11 AA WW
 22 BB KK
 13毫升LL

或者,如果你只是想要一个单行,做到这一点:

 的awk'BEGIN {行= 0;} / ,, / {行= 0;}!/ ,, / {A [行++] = A [行]$ 0; } END {为(我的)打印[I]}'数据文件

编辑:

这将添加字段之间用逗号:

 的awk'BEGIN {行= 0;} / ,, / {行= 0;}!/ ,, / {A [行++] = A [线] A [行? ],$ 0:$ 0;} {结束了(我的)打印[I]}'数据文件
                                                              #^这是我改变的部分

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

解决方案

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

这篇关于Linux的在同一个CSV文件分割成列的两个不同的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆