简体   繁体   中英

sed help: matching and replacing a literal “\n” (not the newline)

i have a file which contains several instances of \\n .

i would like to replace them with actual newlines, but sed doesn't recognize the \\n .

i tried

sed -r -e 's/\n/\n/'
sed -r -e 's/\\n/\n/'
sed -r -e 's/[\n]/\n/'

and many other ways of escaping it.

is sed able to recognize a literal \\n ? if so, how?

is there another program that can read the file interpreting the \\n 's as real newlines?

你可以试试这个吗

sed -i 's/\\n/\n/g' input_filename
$ echo "\n" | sed -e 's/[\\][n]/hello/'

awk seems to handle this fine:

echo "test \n more data" | awk '{sub(/\\n/,"**")}1'
test ** more data

Here you need to escape the \\ using \\\\

1) sed work 1 line ata time son no \\n on 1 line only (it's removed by sed at read time into buffer). You should use N,n or H, h to fill the buffer with more than 1 line, and than \\n appear inside. Be carreful, ^ and $ are no more end of line but end of string/buffer so \\n are inside. 2) \\n is recognize in search pattern, not in replace pattern. 2 ways for using it (sample)

sed s/\(\n\)bla/\1blabla\1/
sed s/\nbla/\
blabla\
/

first use a \\n already inside as back reference (smaller line in replace pattern) second use a real new line

so basicaly

sed "N
$ s/\(\n\)/\1/g
"

work (but is a bit useless). I imagine that s/\\(\\n\\)\\n/\\1/g is more what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM