Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

regex - Replace newlines with literal

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

This works, but not for special characters like , , etc.

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

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

and

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

also

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

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

Thoughts?

Edited after first answer:

For the sake of completeness the commands run are :

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

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"}]}]}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is this all you're trying to do?

$ cat file
a
b
c

$ awk '{printf "%s\n", $0}' file
a
b
c
$

or even:

$ awk -v ORS='\n' '1' file
a
b
c
$

Run dos2unix on the input file first to strip the s if you like, or use -v RS=' ? ' with GNU awk or do sub(/ $/,""); before the printf or any other of a dozen or so clear, simple ways to handle it.

sed is for simple substitutions on individual lines, that is all. For anything else you should be using awk.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...