Warm tip: This article is reproduced from serverfault.com, please click

bash-在ubuntu中用\ n替换双引号之间的换行符

(bash - replace new line character between double quotes with \n in ubuntu)

发布于 2020-11-30 14:44:40

数据样本输入:

Name    mobile  url message text
test11  1234567890  www.google.com  "Data Test New
Date:27/02/2020
sample1: 1bags
sample2: 20bags
Regards
The test user user user Sangha
Ph:091 : 123456789"
test12  1234567891   www.google.com  hello

我的输出应该是

Name    mobile  url message text
test11  1234567890  www.google.com  "Data Test New\nDate:27/02/2020\nsample1: 1bags\nsample2: 20bags\nRegards\nThe test user user user Sangha\nPh:091 : 123456789"
test12  1234567891  www.google.com  hello

我已经使用了以下命令,但是它不起作用

awk '!/"$/{sub(/$/,"\\n");printf "%s",$0;next}1' file

我也使用了其他几个命令,但是在我的情况下它们都不起作用

Questioner
user13000875
Viewed
0
anubhava 2020-12-01 00:19:35

使用gnu-awk,你可以这样做:

awk -v RS='"[^"]*"' '{gsub(/\r?\n/, "\\n", RT); ORS=RT} 1' file

Name    mobile  url message text
test11  1234567890  www.google.com  "Data Test New\nDate:27/02/2020\nItems: 1\nTotal: 3\nRegards\nABC DATa\nPh:091 : 123456789"
test12  1234567891   www.google.com  hello

代码演示