只是想知道如何在字段周围添加单引号,这样我就可以将其导入 mysql 而不会出现警告或错误。
我有一个包含大量内容的 csv 文件。
16:47:11,3,r-4-VM,250000000.,0.50822578824,131072,0,0,0,0,0
期望的输出
'16:47:07','3','r-4-VM','230000000.','0.466028518635','131072','0','0','0','60','0'
我真的不知道从哪里开始,非常感谢您的帮助。
你可以试试这个
awk -F"," -v quote="'" -v OFS="','" '$1=$1 {print quote $0 quote}' file
(-F"," -v OFS="','")
(print quote $0 quote)
try this:
awk '{gsub(/^|$/,"\x027");gsub(/,/,"\x027,\x027")}7' file
example
kent$ echo "16:47:11,3,r-4-VM,250000000.,0.50822578824,131072,0,0,0,0,0"|awk '{gsub(/^|$/,"\x027");gsub(/,/,"\x027,\x027")}7'
'16:47:11','3','r-4-VM','250000000.','0.50822578824','131072','0','0','0','0','0'
这可能对您有用(GNU sed):
sed -r 's/[^,]+/'\''&'\''/g' file
或者:
sed -r "s/[^,]+/'&'/g" file
#!/usr/bin/awk -f
BEGIN { FS=OFS=","}
{
for (i = 1; i <= NF; ++i)
$i = "'" $i "'"
print
}
At the beginning, set FS
(the field separator) to a comma; also set OFS
, the output field separator, to a comma.
For every input line, loop over all fields. NF
is the number of fields parsed out of the current line. Set each field to its own value surrounded by single quotes.
When done updating the fields, print the modified line.
awk 'BEGIN{FS=OFS=","}{for (i=1;i<=NF;++i) $i="~"$i"~"}{print}' $input_csv_file
这行得通。在这里,我将所有 csv 文件列都用~
.
awk
并且sed
不会(轻松)确定字段分隔符 ( ,
) 是否被转义。csv 文件格式,
通过将整个字段括在双引号中来转义字段中的字符(请参阅RFC4180的第 2.6 节)。
正如我在这个答案中所描述的,一种更强大的方法是使用 csv 库,而不是使用正则表达式等解析为文本。
我发现 Python 的库是最好的选择,因为它是:
根据问题的标签,我怀疑这些标准也会吸引你。
因此,请尝试以下操作:
QUOTE_CSV_PY="import sys; import csv; csv.writer(sys.stdout, quoting=csv.QUOTE_ALL, quotechar=\"'\").writerows(csv.reader(sys.stdin))"
python -c "$QUOTE_CSV_PY" < file
分解它:
QUOTE_CSV_PY
是一个包含 Python 单行命令的 shell 变量stdout
),QUOTE_ALL
以便所有字段都使用 引用quotechar
,它设置为单引号;stdin
。file
)输入到它的stdin
.