2011-03-22 77 views
0

假设我有以下文件。如何告诉awk使用=作为分隔符(同时删除空格)

John=good 
Tom = ok 
Tim = excellent 

我知道下面就让的我用=作为分隔符。

awk -F= '{print $1,$2}' file 

这给了我以下结果。

John good 
Tom  ok 
Tim  excellent 

我想要忽略空格,以便只打印出名称和它们的性能。

解决此问题的一种方法是对结果运行另一个awk

awk -F= '{print$1,$2}' file | awk '{print $1,$2}' 

但我想知道我是否可以在一个awk中做到这一点?

回答

4

将它们包含在分隔符定义中;这是一个正则表达式。

jinx:1654 Z$ awk -F' *= *' '{print $1, $2}' foo.ds 
John good 
Tom ok 
Tim excellent 
+0

这是太快了。谢谢。 – Russell 2011-03-22 20:36:33

1

FS变量可以被设置为正则表达式。

从AWK手册

The following table summarizes how fields are split, based on the value of FS. 

FS == " " 
    Fields are separated by runs of whitespace. Leading and trailing whitespace are ignored. This is the default. 
FS == any single character 
    Fields are separated by each occurrence of the character. Multiple successive occurrences delimit empty fields, as do leading and trailing occurrences. 
FS == regexp 
    Fields are separated by occurrences of characters that match regexp. Leading and trailing matches of regexp delimit empty fields. 
相关问题