用文字替换换行符 \n [英] Replace newlines with literal \n

查看:60
本文介绍了用文字替换换行符 \n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个stackoverflow问题有一个答案用 sed 替换换行符,使用格式 sed ':a;N;$!ba;s/\n//g'.

This stackoverflow question has an answer to replace newlines with sed, using the format sed ':a;N;$!ba;s/\n/ /g'.

这有效,但不适用于 \r、\n 等特殊字符

This works, but not for special characters like \r, \n, etc.

我想要做的是用文字 \n 替换换行符.试过

What I'm trying to do is to replace the newline character by a literal \n. Tried

sed ':a;N;$!ba;s/\n/\\n/g'

sed ':a;N;$!ba;s/\n/\\\n/g'

还有

sed ":a;N;$!ba;s/\n/'\'n/g"

但都无济于事.Sed 不断用换行符替换换行符....

but all to no avail. Sed keeps replacing the newline character.... with a newline character.

想法?

为了完整起见,运行的命令是:

For the sake of completeness the commands run are :

PostContent=cat $TextTable |sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g'

PostContent=cat $TextTable | sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g'

其中 TextTable 是链接到包含以下格式的 JSON 输出的文本文件的变量:

Where TextTable is a variable linking to a text file containing a JSON output in the following format :

{"posts":[{"title":"mysupertest","slug":"bi-test","markdown":"##TEST
First things first !
To TEST this TEST TEST, click the download button below.
If you need more information about the TEST TEST, you can  read the Table of Contents below.

<a href='/assets/TEST.pdf' style='border-radius:5px; padding: 4px 15px; background-color:#008CBA; color:white; text-decoration:none; float:right;' download> Download </a>


##TEST OF TEST


###TEST TEST PLATFORM TEST GUIDE
WaTESTve TEST SetupTEST
TESTTEST
TESTTESTETESTTETSTTEST
TESTTESTTTETST
TESTTES
TESTTESTESSTSTESTESTTES
TEST","image":"http://localhost:3000/myimage.jpg","featured":false,"page":false,"status":"draft","language":"en_US","meta_title":null,"meta_description":null,"author":"4","publishedBy":null,"tags":[{"uuid":"ember2034","name":"implementation guides","slug":null,"description":null,"meta_title":null,"meta_description":null,"image":null,"visibility":"public"}]}]}

推荐答案

这应该适用于 LFCR-LF 行尾:

This should work with both LF or CR-LF line endings:

sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g' file

这篇关于用文字替换换行符 \n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆