问题描述
|
这里有一个类似的问题,但是对于excel / vba Excel宏-逗号分隔的单元格到行保留/汇总列
因为我有一个大文件(> 300mb),所以这不是一个选择,因此我正在努力使其以bash的形式工作。
基于此数据
1 Cat1 a,b,c
2 Cat2 d
3 Cat3 e
4 Cat4 f,g
我想将其转换为:
1 Cat1 a
1 Cat1 b
1 Cat1 c
2 Cat2 d
3 Cat3 e
4 Cat4 f
4 Cat4 g
解决方法
cat > data << EOF
1 Cat1 a,b,c
2 Cat2 d
3 Cat3 e
4 Cat4 f,g
EOF
set -f # turn off globbing
IFS=,# prepare for comma-separated data
while IFS=$\'\\t\' read C1 C2 C3; do # split columns at tabs
for X in $C3; do # split C3 at commas (due to IFS)
printf \'%s\\t%s\\t%s\\n\' \"$C1\" \"$C2\" \"$X\"
done
done < data
,这看起来像是awk或perl的工作。
awk \'BEGIN { FS = OFS = \"\\t\" }
{ split($3,a,\",\");
for (i in a) {$3 = a[i]; print} }\'
perl -F\'\\t\' -alne \'foreach (split \",$F[2]) {
$F[2] = $_; print join(\"\\t\",@F)
}\'
这两个程序都基于相同的算法:以逗号分隔第三列,并遍历组件,依次在第三列中打印每个组件的原始行。