如何在从文件中读取时忽略空格和逗号

时间:2016-01-27 18:09:56

标签: shell unix awk ksh

我有一个逗号分隔文件,我需要从每一行中提取第三个字段。文件test.txt包含以下内容:

6,STRING TO DECIMAL WITHOUT DEFAULT,cast($src_fld as DECIMAL(15,2) $tgt_fld 
7,STRING TO INTERGER WITHOUT DEFAULT,cast($src_fld as integer) $tgt_fld                
10,DEFAULT NO RULE,'$default' $tgt_fld
  

cat test.txt | awk -F,' {print $ 3}'

如果我写上面的命令,我得到一个不正确的输出:

> cast($src_fld as DECIMAL(15
> cast($src_fld as integer) $tgt_fld
> '$default' $tgt_fld

任何人都可以告诉我如何实现它。我需要在循环中编写它,以便以后可以进行进一步处理。请注意,每个第三个字段可能包含空格和逗号(,)。

5 个答案:

答案 0 :(得分:2)

awk救援!

不是一般解决方案,但适用于您的格式

$ awk -F, '{for(i=4;i<=NF;i++) $3 = $3 FS $i} {print $3}' badcsv

cast($src_fld as DECIMAL(15,2) $tgt_fld
cast($src_fld as integer) $tgt_fld
'$default' $tgt_fld

解释您正在根据FS =“,”打印第二个字段后的文本部分。该脚本在打印前将其余字段附加在$ 3上。

答案 1 :(得分:2)

正如您所说,前两个字段不包含逗号,您可以使用逗号作为字段分隔符的cut

$ cut -d ',' -f 3- test.txt 
cast($src_fld as DECIMAL(15,2) $tgt_fld 
cast($src_fld as integer) $tgt_fld                
'$default' $tgt_fld

答案 2 :(得分:1)

如果前两个字段中有逗号,则无法执行任务。

1,second,field,with,commas,third,field,with,commas

您无法知道第二个字段的结束位置以及第三个字段的开始位置。

您必须使用实际的CSV语法,并使用CSV解析器解析文件。

1,"second,field,with,commas","third,field,with,commas"

如果您可以确定前两个字段中没有逗号,则可以执行以下操作:

sed 's/^[^,]\+,[^,]\+,//' file

答案 3 :(得分:0)

你没有告诉我们正确的输出是什么,只是它不是什么,所以这是你可能想要的猜测,但你应该能够弄清楚你需要什么这不是很正确:

$ cat tst.awk
BEGIN { FS="," }
{
    $0 = gensub(/([(][^()]+),([^()]+[)])/,"\\1"RS"\\2","g",$0)
    for (i=1; i<=NF; i++) {
        gsub(RS,FS,$i)
        print NR, NF, i, $i
    }
    print "----"
}

$ awk -f tst.awk file
1 3 1 6
1 3 2 STRING TO DECIMAL WITHOUT DEFAULT
1 3 3 cast($src_fld as DECIMAL(15,2) $tgt_fld
----
2 3 1 7
2 3 2 STRING TO INTERGER WITHOUT DEFAULT
2 3 3 cast($src_fld as integer) $tgt_fld
----
3 3 1 10
3 3 2 DEFAULT NO RULE
3 3 3 '$default' $tgt_fld
----

以上使用GNU awk for gensub(),其他awks使用match()+ substr()。

答案 4 :(得分:0)

如果要使用循环,可以使用

if(*str1 == *str2)   
相关问题