如何将换行符转换为文字“\n”

How to convert linefeed into literal "\n"

我在将文件转换为格式正确的 json 字符串时遇到了一些问题。 已经摆弄 sed 好久了,但它似乎在嘲笑我。 如果重要的话,我正在研究 RHEL 6。

我正在尝试转换此文件(内容):

Hi there...

foo=bar
tomàto=tomáto
url=http://www.whosebug.com

进入这个 json 字符串:

{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.whosebug.com"} 

如何替换文字“\n”字符中的实际换行符?这就是我完全陷入困境的地方!

我一直在尝试将换行符转换为“;”首先然后返回到文字“\n”。为文件中的每一行尝试循环。无法正常工作...

非常感谢您的帮助! 谢谢!

awk 救援!

$ awk -vRS='[=10=]' '{gsub("\n","\n"); 
                  print "{\"text\":\"" [=10=] "\"}"}' file

{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.whosebug.com\n"}

使用 GNU sed:

sed ':a;N;s/\n/\n/;ta' file | sed 's/.*/{"text":"&"}/'

输出:

{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.whosebug.com"}

为此使用 awk :

awk -v RS=^$ '{gsub(/\n/,"\n");sub(/^/,"{\"text\":\"");sub(/\n$/,"\"}")}1' file

输出

{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.whosebug.com"}

sed 用于在单行上进行简单替换,仅此而已。由于 sed 逐行工作,因此您的 sed 脚本看不到行尾,因此如果不使用神秘的语言结构和自 1970 年代中期以来就没有用过的复杂逻辑,您就无法更改行尾而不跳过箍awk 是什么时候发明的。

这会将输入文件中的所有换行符更改为字符串 \n:

$ awk -v ORS='\n' '1' file
Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.whosebug.com\n

这将完成剩下的工作:

$ awk -v ORS='\n' 'BEGIN{printf "{\"text\":\""} 1; END{printf "\"}\n"}' file
{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.whosebug.com\n"}

或者,如果您在输入文件末尾有一个换行符但不希望它在输出中变成 \n 字符串:

$ awk -v ORS='\n' '{rec = (NR>1 ? rec ORS : "") [=12=]} END{printf "{\"text\":\"%s\"}\n", rec}' file
{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.whosebug.com"}

这可能对你有用 (GNU sed):

sed '1h;1!H;$!d;x;s/.*/"text":"&"/;s/\n/\n/g' file

将文件 Slurp 到内存中并使用模式匹配将文件操作为所需格式。

最简单(优雅?)的解决方案:) :

#!/bin/bash

in=$(perl -pe 's/\n/\n/' )

cat<<EOF
{"text":"$in"} 
EOF

用法:

./script.sh file.txt

输出:

{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.whosebug.com\n"}