2013-04-16 147 views
1

我有以下CSV文件:bash的换行符替换成引号

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

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


data" 

我想通过字符\n全部更换为新行(Windows或UNIX风格),所以我将获得:

"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 
}' 
+0

您可以通过替换做到这一点'\([^“] \)\ n \(。\)'用'\ 1 \\ n \ 2'(例如使用Perl) –

回答

1

这里有一个方法:

$ 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" 
1

做这项工作˚F或者你?两行相同的想法

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" 
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