bash paste不保留换行符

时间:2015-02-24 14:45:37

标签: linux bash paste

我的bash脚本从file1.txt粘贴,它逐行输入CSV格式。例如:

File1.txt包含文字:

John
21-2-2015
some city
"108 Brent Street
Ridgewoods
sometown
somecountry"

CSV上传的转换后的输出应如下所示:

John,21-2-2015,some city,"108 Brent Street
Ridgewoods
sometown
somecountry"

但是我的代码会将其转换为:

John,21-2-2015,some city,"108 Brent Street Ridgewoods sometown somecountry"

我想保留换行符。

我的代码:

paste -sd, file1.txt > file2.csv

2 个答案:

答案 0 :(得分:1)

你可以尝试下面的Perl命令。

$ perl -0777pe 's/(?s)"[^"]*"(*SKIP)(*F)|\n(?!$)/,/g' file
John,21-2-2015,some city,"108 Brent Street
Ridgewoods
sometown
somecountry"

添加-i参数以保存对该文件所做的更改。

答案 1 :(得分:1)

您可以使用GNU FPAT

awk功能
cat main.awk
BEGIN { 
   FPAT = "([^\n]+)|(\"[^\"]+\")"
   OFS=","
   RS=""
   ORS="\n"
}
{ $1=$1; print
}
awk -f main.awk <datafile
John,21-2-2015,some city,"108 Brent Street
Ridgewood
sometown
somecountry"