如何使用unix在某一列中添加单引号
how to add single quotes in a certain column using unix
输入:
101,ravi,chennai
101,kavi,mumbai
101,pavi,delhi
输出:
101,'ravi','chennai'
102,'Kavi','mumbai'
103,'Pavi','delhi'
使用sed
:
sed "s/,\([^,]*\)/,''/g" file
将逗号后跟任何非逗号字符(用 \(...\)
捕获)替换为逗号、单引号、捕获组和单引号。替换是在 g
局部完成的。
使用awk
引用第二个和第三个字段:
awk 'BEGIN{ FS=OFS="," }
NF==0 { print; next }
{
printf # print first field
for (i=2;i<=NF;i++){
# print comma and the next field
printf OFS (i==2||i==3 ? "'\''" $i "'\''" : $i)
}
printf ORS # print newline
}
' file
输入:
101,ravi,chennai
101,kavi,mumbai
101,pavi,delhi
输出: 101,'ravi','chennai'
102,'Kavi','mumbai'
103,'Pavi','delhi'
使用sed
:
sed "s/,\([^,]*\)/,''/g" file
将逗号后跟任何非逗号字符(用 \(...\)
捕获)替换为逗号、单引号、捕获组和单引号。替换是在 g
局部完成的。
使用awk
引用第二个和第三个字段:
awk 'BEGIN{ FS=OFS="," }
NF==0 { print; next }
{
printf # print first field
for (i=2;i<=NF;i++){
# print comma and the next field
printf OFS (i==2||i==3 ? "'\''" $i "'\''" : $i)
}
printf ORS # print newline
}
' file