运行awk脚本时出现语法错误,脚本为:
awk -F\" 'for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,,,$1) }}'
实际数据的样子如下(封闭和管道分开):
"data"|"data"|"data"|"data"|"data"
我想要做的是,从代码中可以看出:读取所有字段,如果字段是数字(将始终为十进制),请用逗号替换该点。 我也试图逃避gsub函数中的逗号:
awk -F\" 'for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,\,,$1) }}'
但它没有解决问题,你知道问题出在哪里吗?与正则表达式的比较看起来很好,循环和if语句也是,错误信息是
awk: cmd. line:1: for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,,,$1) }}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,,,$1) }}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,,,$1) }}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,,,$1) }}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,,,$1) }}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,,,$1) }}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,,,$1) }}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: for( i = 1 ; i <= NF; i++){if ($i == "^[0-9]+$"){ gsub(.,,,$1) }}
awk: cmd. line:1: ^ 1 is invalid as number of arguments for gsub
答案 0 :(得分:1)
此行可能适合您:
awk 'BEGIN{FS=OFS="\""}{for(i=1;i<=NF;i++)if($i~/[0-9\.]*/)gsub("\\.",",",$i)}1' file
测试:
kent$ echo '"1000.18"|"4.8"|"data"|"data"|"3.5"'|awk 'BEGIN{FS=OFS="\""}{for(i=1;i<=NF;i++)if($i~/[0-9\.]*/)gsub("\\.",",",$i)}1'
"1000,18"|"4,8"|"data"|"data"|"3,5"
代码中的问题是:
{}
~
,而不是==
进行正则表达式匹配^[0-9]+$
仅匹配数字,20.8不匹配。因为有一个点答案 1 :(得分:0)
你之前缺少一个Curly大括号。 你可以试试这个
awk -F\" '{for(i=1;i<=NF;i++){if($i=="^[0-9]+$"){gsub(".",",",$1); }}}'