在每列的末尾添加一个模式

时间:2015-03-04 18:33:59

标签: awk sed

假设我有一个类似于这种格式的文件:

"pop","hand stuff","test "
"non","no way","good "

除了只有3列它有数百个。我想在每列的末尾添加@,因此输出为

"pop@","hand stuff@","test @"
"non@","no way@","good @"

如果我只有少量列,那么我可以做

awk -F"," vOFS=, '{print $1"@",$2"@",$3"@"}'

但如果我有很多列并且我不想在awk脚本中指定每一列,我该如何做?

3 个答案:

答案 0 :(得分:1)

你可以使用像下面这样的awk&#39s gsub函数。

awk '{gsub(/",/, "@\",");sub(/"$/, "@\"")}1' file

示例:

$ echo '"pop","hand stuff","test "' | awk '{gsub(/",/, "@\",");sub(/"$/, "@\"")}1'
"pop@","hand stuff@","test @"

答案 1 :(得分:1)

只要您的专栏不包含疯狂数据(特别是字符串中嵌入\",),sed就会更容易:

OSX / BSD:

sed -E 's/"(,|$)/@"\1/g' 

GNU:

sed -r 's/"(,|$)/@"\1/g' 

答案 2 :(得分:1)

$ sed -r 's/("[^"]+)"/\1@"/g' file
"pop@","hand stuff@","test @"
"non@","no way@","good @"