我有一个来自SO的人提供的脚本来解决我遇到的问题,但是,我在使用OSX时遇到了一些问题。
gawk --version
GNU Awk 3.1.6
awk --version
awk version 20100208
原始来源是:
awk -F, -vOFS=, -vc=1 '
NR == 1 {
for (i=1; i<NF; i++) {
if ($i != "") {
g[c]=i;
f[c++]=$i
}
}
}
NR>2 {
for (i=1; i < c; i++) {
print $1,$2, $g[i] > "output_"f[i]".csv
}
}' data.csv
当我运行脚本时,它会出现以下错误:
awk: syntax error at source line 12
context is print $1,$2, $g[i] > >>> "output_"f <<< [i]".csv
awk: illegal statement at source line 13
从它的外观来看,[i]的变量没有被修改为输出文件,但我不知道为什么。
如果我将AWK更改为GAWK并运行原始脚本,则输出为:
gawk: cmd. line:11: print $1,$2, $g[i] > "output_"f[i]".csv
gawk: cmd. line:11: ^ unterminated string
所以我编辑相关的行来修复未终止的字符串
print $1,$2, $g[i] > "output_"f[i]".csv"
然后它运行良好产生没有错误,但没有输出文件。
有什么想法吗?我昨晚花了大部分时间,今天早上一直在这上面。
示例输入文件:
,,L1,,,L2,,,L3,,,L4,,,L5,,,L6,,,L7,,,L8,,,L9,,,L10,,,L11,
Title,r/t,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,neede d,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst
EXAMPLEfoo,60,6,6,6,0,0,0,0,0,0,6,6,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
EXAMPLEbar,30,6,6,12,6,7,14,6,6,12,6,6,12,6,8,16,6,7,14,6,7.5,15,6,6,12,6,8,16,6,0,0,6,7,14
EXAMPLE1,60,3,3,3,3,5,5,3,4,4,3,3,3,3,6,6,3,4,4,3,3,3,3,4,4,3,8,8,3,0,0,3,4,4
EXAMPLE2,120,6,6,3,0,0,0,6,8,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
EXAMPLE3,60,6,6,6,6,8,8,6,6,6,6,6,6,0,0,0,0,0,0,6,8,8,6,6,6,0,0,0,0,0,0,0,10,10
EXAMPLE4,30,6,6,12,6,7,14,6,6,12,6,6,12,3,5.5,11,6,7.5,15,6,6,12,6,0,0,6,9,18,6,0,0,6,6.5,13
示例输出应该是
因此,对于L1,一个例子输出看起来像:
EXAMPLEfoo,60,6
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,6
EXAMPLE3,60,6
EXAMPLE4,30,6
对于L2:
EXAMPLEfoo,60,0
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,0
EXAMPLE3,60,6
EXAMPLE4,30,6
答案 0 :(得分:1)
我看到两个问题(在OS X平台上):
这是我的解决方案,它似乎适用于Mac OS X Snow Leopard和Red Hat Linux 4.x:
awk -F, '
BEGIN { OFS=","; c=1 } # FIX problem 1
NR == 1 {
for (i=1; i<NF; i++) {
if ($i != "") {
g[c]=i;
f[c++]=$i
}
}
}
NR>2 {
for (i=1; i < c; i++) {
outfile=sprintf("output_%s.csv", f[i]) # FIX problem 2
print $1,$2, $g[i] > outfile
}
}' data.csv