将 \n", 替换为 ", [重复]

Posted

技术标签:

【中文标题】将 \\n", 替换为 ", [重复]【英文标题】:Replace \n", with ", [duplicate]将 \n", 替换为 ", [重复] 【发布时间】:2014-02-20 13:03:20 【问题描述】:

我的文件中有如下格式的数据

"253539","","Company1 Name  
","0","1"
"255229","","Ramu ","0","1"
"253548","","Mater Name/Id 
","0","1"
"255229","","Ram Lakh","0","1"
"253619","","CHild Name/Ids 
","0","1"

每一行都附加了\n。

如何在 shell 脚本中将 \n", 替换为 ", 以获取输出为

"253539","","Company1 Name/Id  ","0","1"
"255229","","Ramu ","0","1"
"253548","","Mater Name/Id ","0","1"
"255229","","Ram Lakh","0","1"
"253619","","CHild Name/Id ","0","1"

需要自动化一个过程,所以必须写在 shell 脚本中。

请帮忙。

【问题讨论】:

【参考方案1】:

不确定是否可以在 shell 中轻松完成此操作,但我制作了一个一次性的 Perl 脚本来执行此操作:

perl -e 'foreach (<>)  chop; print; print "\n" if /"$/ ' < mydata.csv

仅当行以" 结尾时才输出换行符。

【讨论】:

【参考方案2】:

可以做类似的事情

#!/bin/bash

while read -r line; do
 [[ $line =~ '"'$ ]] && echo "$line" || echo -n "$line"
done < file

例如在您的输入文件上

> ./abovescript
"253539","","Company1 Name","0","1"
"255229","","Ramu ","0","1"
"253548","","Mater Name/Id","0","1"
"255229","","Ram Lakh","0","1"
"253619","","CHild Name/Ids","0","1"

【讨论】:

【参考方案3】:

使用awk,您可以:

$ awk '/"$/ print a$0; a=""; next a=$0' file
"253539","","Company1 Name  ","0","1"
"255229","","Ramu ","0","1"
"253548","","Mater Name/Id ","0","1"
"255229","","Ram Lakh","0","1"
"253619","","CHild Name/Ids ","0","1"

它的作用是将行存储在a 中,以防它不以" 结尾。如果是,则打印存储的行加上当前行。

【讨论】:

【参考方案4】:

如果@fedorqui 的回答可以被接受,那么这里是较短的代码。

awk 'printf $0 (/"$/?RS:X)' file

【讨论】:

以上是关于将 \n", 替换为 ", [重复]的主要内容,如果未能解决你的问题,请参考以下文章

.htaccess 将“/”替换为“_”

正则表达式用除以 2 替换 "\n" 出现

Java:将 \" 替换为 " 和 \/ 替换为 /

替换有时加倍的字符的单个实例

正则替换换行符和把 br 替换成换行符

sed命令中如何讲一个特殊字符(比如"")替换为换行符?