awk - 如果字符串不是以双引号开头,则在字符串中添加双引号
问题描述
我有一个这样的文本文件:
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
. 请帮助。谢谢!
解决方案
以下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"
推荐阅读
- django - 如何从 Django 模型中 ImageField 的图像目录中选择一个随机图像?
- android - 仅在从 android studio 的 Datepickerdialog 中选择之后,如何才能显示选定的日期和名称?
- c# - 模型中的虚拟字段在保存时出错
- pdf - 通过使用 Ghostscript 向 PDF 添加边距来缩放页面中的图像
- angular - Angular 2+ npm 启动问题
- abstract-syntax-tree - AST 节点中的“nosink”
- javascript - Collada 从未在 animate() 中定义
- javascript - 单击重置按钮时如何恢复输入框的默认值(即今天的日期或当前日期)?
- android - 调用 Fragment 构造函数导致异常。导航架构组件
- php - PHP错误,无法将图像插入数据库