在awk中将split数组设置为空

时间:2013-10-31 16:21:31

标签: bash awk

我有以下文件

Hello. this is an example
    Car=toyota Fruit=Orange Name=John
    01
    Car=toyota Fruit=Orange Name=John
    02
    Car=toyota Fruit=Orange Name=John
    03
End of the file

我在shell中运行这个awk代码

awk -F "\t" '{n=split($2,a); for(i=1 ; i<=n ; i++) {if(a[i] ~ "^Fruit*") a[i]=""} print}' myFile.txt

所以字段分隔符是tab。然后我使用space拆分第二个字段。如果我的任何子字段(以空格分隔)以Fruit开头,我想删除它。

这不起作用。它不会删除它。


预期输出

Hello. this is an example
    Car=toyota Name=John
    01
    Car=toyota Name=John
    02
    Car=toyota Name=John
    03
End of the file

请不要使用额外的包裹。我希望它尽可能默认。 (使用awk,sed,grep会很棒)

3 个答案:

答案 0 :(得分:3)

  

如果我的任何子字段(以空格分隔)以   Fruit我想将其删除。

您可以使用sed

$ sed 's/Fruit=[^ ]* //g' inputfile
Hello. this is an example
    Car=toyota Name=John
    01
    Car=toyota Name=John
    02
    Car=toyota Name=John
    03
End of the file

答案 1 :(得分:2)

awk   '{gsub(/ Fruit[^ ]*/,"")}1' myFile.txt

给出:

Hello. this is an example
    Car=toyota Name=John
    01
    Car=toyota Name=John
    02
    Car=toyota Name=John
    03
End of the file

答案 2 :(得分:2)

$ cat file                                                          
Hello. this is an example
    Car=toyota ForeName=John Name=JohnSmith 
    01
End of the file

$ sed -r 's/(^|[[:space:]])ForeName=[^[:space:]]+[[:space:]]*/\1/' file
Hello. this is an example
    Car=toyota Name=JohnSmith 
    01
End of the file

$ sed -r 's/(^|[[:space:]])Name=[^[:space:]]+[[:space:]]*/\1/' file    
Hello. this is an example
    Car=toyota ForeName=John 
    01
End of the file