2013-12-10 109 views
1

everyone如何讓awk尊重字段分隔符?

我把一行傳給awk,逗號作爲字段分隔符。我想awk生成仍然使用逗號作爲分隔符的輸出。但awk將逗號更改爲空格。

echo "qwer,asdf,zxcv" | awk -F',' '{gsub("a","b",$2); print $0}' 
qwer bsdf zxcv 

有沒有辦法讓awk尊重原始輸入的分隔符?

回答

2

定義OFS,即,輸出字段分隔符:

$ echo "qwer,asdf,zxcv" | awk -F',' 'BEGIN{OFS=","}{gsub("a","b",$2); print $0}' 
qwer,bsdf,zxcv 

還要注意,{print $0}可被跳過並且-F也包含在BEGIN{}塊:

$ echo "qwer,asdf,zxcv" | awk 'BEGIN{FS=OFS=","}{gsub("a","b",$2)} 1' 
qwer,bsdf,zxcv 

給人一種1我們給出一個真實條件,默認爲{print $0}

3

你可以這樣做與awk

echo "qwer,asdf,zxcv" | awk -F, '{gsub("a","b",$2); print $0}' OFS=, 
qwer,bsdf,zxcv