Escape CSV file with sed or other command line too

2019-09-23 08:33发布

I have the following CSV, separated by "|".

101|abc|this is desc|2017
102|xyz|"thie is a long desc
des for xyz continue here."|2017

I have two records, 101 and 102. 102 record is divided into 2 lines. How can I used sed or other command line tools to escape the new line character with "/"?

3条回答
何必那么认真
2楼-- · 2019-09-23 08:45
$ sed '/102/ s#$#/&#' file11
101|abc|this is desc|2017
102|xyz|"thie is a long desc/
des for xyz continue here."|2017
查看更多
放荡不羁爱自由
3楼-- · 2019-09-23 08:53

awk is better tool to handle this.

Assuming you know how many columns are needed in each line. You can use this awk command:

awk -v n=4 -F '|' 'p+NF<n{p+=NF-1; print $0 "\\"; next} {p=0} 1' file

101|abc|this is desc|2017
102|xyz|"this is a long desc\
des for xyz continue here."|2017
查看更多
我想做一个坏孩纸
4楼-- · 2019-09-23 08:53

For your specific case you can use this.

$ cat lll 101|abc|this is desc|2017 102|xyz|"thie is a long desc des for xyz continue here."|2017 105|xyz|"thie is a long desc des for xyz continue here."|2017 101|abc|this is desc|2017 101|abc|this is desc|2017 101|abc|this is desc|2017 105|xyz|"thie is a long desc des for xyz continue here."|2017

$ perl -F'\n' -ane 'BEGIN{our $line_to_join = undef; } foreach ( @F) { if (/[a-z]+$/) { $line_to_join = $_; } elsif ($line_to_join){ print $line_to_join,"/\n",$_,"\n"; $line_to_join = undef; }else{print $_,"\n" ; $line_to_join = undef;}} ;' < lll

Output:

101|abc|this is desc|2017 102|xyz|"thie is a long desc/ des for xyz continue here."|2017 105|xyz|"thie is a long desc/ des for xyz continue here."|2017 101|abc|this is desc|2017 101|abc|this is desc|2017 101|abc|this is desc|2017 105|xyz|"thie is a long desc/ des for xyz continue here."|2017

查看更多
登录 后发表回答