首页 > 解决方案 > 如果字符串不是以双引号开头,则在字符串中添加双引号

问题描述

我有一个这样的文本文件:

1,a,"some strings in a pair of double quotes"
2,b,"more strings in a pair of double quotes"
3,c,some messy strings with only right half double quotes"
4.d,"more strings in a pair of double quotes"

我尝试使用 awk 和 sed 将缺少的左双引号添加到第 3 行:

function addQuote(input) {
 return '"' + input
}    
BEGIN{
   FS=","
}

{
  if ($3~/^"/) s = $3
  else s = addQuote($3)

  print $1,$2,s
}

似乎该addQuote功能不起作用,但我不知道如何修复它。

我知道sed我可以通过 do 轻松地在行首添加双引号sed 's/^/"/' line,但我不知道如何使它与awk. 请帮助。谢谢!

标签: awktext-processingcommand-line-tool

解决方案


以下awk可能会对您有所帮助。

awk 'BEGIN{FS=OFS=","} $3 !~ /^"/{$3="\"" $3} 1'  Input_file

或者

awk 'BEGIN{FS=OFS=","} {$3=$3 !~ /^"/?"\"" $3:$3} 1'  Input_file

编辑:根据乔纳森爵士在评论部分的评论,添加以下代码现在将处理 3 个案例,它应该添加"它是否不完全在第三个字段上,它也会添加"字段的最后或字段的开头。

假设我们有以下 Input_file:

cat Input_file
1,a,"some strings in a pair of double quotes"
2,b,"more strings in a pair of double quotes"
3,c,some messy strings with only right half double quotes"
4,d,"more strings in a pair of double quotes
4,d,more strings in a pair of double

现在下面的代码可能涵盖了这里提到的所有 3 个排列/组合:

awk 'BEGIN{FS=OFS=","} {$3=$3 !~ /\"/?"\"" $3 "\"":($3 !~ /^\"/?"\"" $3:($3 !~ /\"$/?$3 "\"":$3))} 1'  Input_file
1,a,"some strings in a pair of double quotes"
2,b,"more strings in a pair of double quotes"
3,c,"some messy strings with only right half double quotes"
4,d,"more strings in a pair of double quotes"
4,d,"more strings in a pair of double"

推荐阅读