我写了一个awk脚本来解析日志文件的输出到exv的tsv,一切都运行正常。然后我想通过从字段中提取子字符串来向tsv添加一个列。但我不能为我的生活得到awk拉出那个子串,甚至将该字段赋给变量。我花了几个小时试图弄清楚发生了什么事无济于事。这是脚本的一部分让我感到沮丧:
printf("$0=%s\n", $0);
printf("$1=%s\n", $1);
printf("$2=%s\n", $2);
inputLine = $0;
cmd = $1;
wavFile = $2;
printf("inputLine=%s\n", $inputLine );
printf("cmd=%s\n", $cmd );
printf("wavFile=%s\n", $wavFile );
uScore = index($wavFile, "_" );
printf("uscore=%d\n", uScore );
ucNum = substr($wavFile, 9, 13 );
testPhrase = substr($2, index($2,"_")+1, length($2) );
printf("ucNUm = %s\n", $ucNum );
printf("testPhrase= %s\n", $testPhrase );
这是产生的输出:
$0=Loading uc60_why_is_that_blinking.wav
$1=Loading
$2=uc60_why_is_that_blinking.wav
inputLine=Loading uc60_why_is_that_blinking.wav
cmd=Loading uc60_why_is_that_blinking.wav
wavFile=Loading uc60_why_is_that_blinking.wav
uscore=13
ucNUm = Loading uc60_why_is_that_blinking.wav
我做错了什么?
感谢.....
感谢Ed的提示。我现在正确分配变量。但我仍然没有分配子串。这是更新的脚本:
printf("$0=%s\n", $0);
printf("$1=%s\n", $1);
printf("$2=%s\n", $2);
inputLine = 0;
cmd = 1;
wavFile = 2;
printf("inputLine=%s\n", $inputLine );
printf("cmd=%s\n", $cmd );
printf("wavFile=%s\n", $wavFile );
uScore = index($wavFile, "_" );
printf("uscore=%d\n", uScore );
ucNum = substr(wavFile, 1, $uScore );
testPhrase = substr(wavFile, $uScore+1, length($wavFile) );
printf("ucNum = %s\n", $ucNum );
printf("testPhrase= %s\n", $testPhrase );
和修改后的输出:
$0=Loading uc60_why_is_that_blinking.wav
$1=Loading
$2=uc60_why_is_that_blinking.wav
inputLine=Loading uc60_why_is_that_blinking.wav
cmd=Loading
wavFile=uc60_why_is_that_blinking.wav
uscore=5
ucNum = Loading uc60_why_is_that_blinking.wav
testPhrase= uc60_why_is_that_blinking.wav
我尝试用substr(wavFile,1,uScore)和substr($ wavFile,1,$ uScore)提取ucNum字符串,但都没有提取子字符串。还有其他想法吗?
答案 0 :(得分:3)
您在awk变量前面使用$
,因此不可取地获取变量整数值引用的字段,而不仅仅是变量的值(或$0
if该变量未设置或其内容为非数字)。
$ echo "foo bar" | awk '{x=1; print "[" x "]\t[" int(x) "]\t[" $x "]"}'
[1] [1] [foo]
$ echo "foo bar" | awk '{ print "[" y "]\t[" int(y) "]\t[" $y "]"}'
[] [0] [foo bar]
$ echo "foo bar" | awk '{z="stuff"; print "[" z "]\t[" int(z) "]\t[" $z "]"}'
[stuff] [0] [foo bar]
查看代码并注意执行所需操作的print语句之间的区别:
printf("uscore=%d\n", uScore );
以及任何不包含的内容,例如:
printf("ucNUm = %s\n", $ucNum );
顺便说一句,落后的半冒号什么也没做,而且这些半身像并没有按照你的想法行事,也可能只是被删除了:
printf "ucNum = %s\n", ucNum
甚至只是:
print "ucNum =", ucNum