2013-04-16 65 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