我有一个 csv 文件,其数据与此类似:
"1b579a5e-9701-40eb-bd36-2bc65169da99","week14_Friday-019","6907eaad-1aff-4d26-9088-ba20374b67c0","2181-019","f20af5bb-c716-42e0-9b9d-cbolf5bfecea","15-BIO-2001","COLLEGE Bio 1","d39330be-df56-4365-8fb4-37e68d040c52","Which engine has the smaller efficiency?","{choices:[a","b","c","d],"type:MultipleChoice}","{solution:[0],"selectAll:false,{"selectMultiple:false",}"type:MultipleChoice}","2016-04-25 00:30:19.000","1922ac5a-6ff6-4ea4-9078-6df4d85d294f","{solution:[0],"type:MultipleChoice}","1","1116911f-8ee5-45c3-b173-a6be681bb15a","FakeLastName","FakeFirstName","[email protected]","Student"
我想删除双引号 ",但前提是它们位于大括号 {} 内部,最好使用 sed 或 awk。所需的输出是:
"1b579a5e-9701-40eb-bd36-2bc65169da99","week14_Friday-019","6907eaad-1aff-4d26-9088-ba20374b67c0","2181-019","f20af5bb-c716-42e0-9b9d-cbolf5bfecea","15-BIO-2001","COLLEGE Bio 1","d39330be-df56-4365-8fb4-37e68d040c52","Which engine has the smaller efficiency?","{choices:[a,b,c,d],type:MultipleChoice}","{solution:[0],selectAll:false,{selectMultiple:false,}type:MultipleChoice}","2016-04-25 00:30:19.000","1922ac5a-6ff6-4ea4-9078-6df4d85d294f","{solution:[0],type:MultipleChoice}","1","1116911f-8ee5-45c3-b173-a6be681bb15a","FakeLastName","FakeFirstName","[email protected]","Student"
任何帮助将不胜感激。谢谢!
答案1
使用以下命令会更容易sed
:
sed -e :1 -e 's/\({[^}]*\)"\([^}]*}\)/\1\2/g; t1'
或者perl
:
perl -pe 's{\{.*?\}}{$& =~ s/"//gr}ge'
请注意,它假设没有嵌套{...}
.
要处理嵌套{...}
,您可以使用perl
的递归正则表达式功能:
perl -pe 's(\{(?:[^{}]++|(?0))*\})($& =~ s/"//gr)ge'
使用 时,在删除 s 之前,sed
先向外扩展以逃避内部s :{...}
"
sed 's/_/_u/g
:1
s/\({[^{}]*\){\([^{}]*\)}/\1_<\2_>/g; t1
:2
s/\({[^}]*\)"\([^}]*}\)/\1\2/g; t2
s/_</{/g; s/_>/}/g;s/_u/_/g'
答案2
尝试使用以下方法sed
:
$ sed -r ' :L; s/(\{[^"}]*)"(([^"}]*")*)([^"}]*\})/\1\2\4/g; tL; ' file
答案3
awk
对于嵌套大括号:
awk -F{ '
{for (i=2; i<=NF; i++) {if (1 == n = split ($i, T, "}")) n++
for (j=1; j<n; j++) {RS = index ($i, T[j])
L = gsub (/"/, _, T[j])
$i = substr ($i, 1, RS-1) T[j] substr ($i, RS + length (T[j]) + L)
}
}
}
1' OFS="{" file
笨拙,但会产生指定的输出,至少对于单嵌套大括号来说是这样。