2011-03-22 75 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. 
相關問題