2

我有以下 CSV 文件:

"test","test2","test
3 and some other

data"
"test4","test5","test6 and some other


data"

我想用字符替换所有换行符(windows或unix样式)\n,所以我会得到:

"test","test2","test\n3 and some other\n\ndata"
"test4","test5","test6 and some other\n\n\ndata"

我试过awk但没有成功:

cat myFile.csv | awk -F \" -v OFS=\" '{
   for (i=0; i<NF; i++) {
      gsub("\\n", "\\\\n", $i)
   }
   print
}'
4

3 回答 3

2

这是一种方法:

$ awk '!/"$/{sub(/$/,"\\n");printf "%s",$0;next}1' file
"test","test2","test\n3 and some other\n\ndata"
"test4","test5","test6 and some other\n\n\ndata"
于 2013-04-16T12:21:05.070 回答
1

这可能对您有用(GNU sed):

sed -r ':a;/^("[^"]*",?){3}$/!{$!N;s/\n/\\n/;ta};P;D' file

或在紧要关头:

 sed ':a;/"$/!{$!N;s/\n/\\n/;ta};P;D' file
于 2013-04-16T13:12:45.883 回答
1

这对你有用吗?具有相同想法的两条线

awk -v RS="\0"  '{gsub(/\n/,"\\n");sub(/\\n$/,"");gsub(/"\\n"/,"\"\n\"");}1' file      

或者

awk -v RS="\0" -v ORS="" '{gsub(/\n/,"\\n");sub(/\\n$/,"\n");gsub(/"\\n"/,"\"\n\"")}1' file

使用您的数据:

kent$  cat file
"test","test2","test
3 and some other

data"
"test4","test5","test6 and some other


data"

输出:

kent$  awk -v RS="\0" -v ORS="" '{gsub(/\n/,"\\n");sub(/\\n$/,"\n");gsub(/"\\n"/,"\"\n\"")}1' file
"test","test2","test\n3 and some other\n\ndata"
"test4","test5","test6 and some other\n\n\ndata"
于 2013-04-16T12:16:56.887 回答