简体   繁体   中英

escaping newlines in sed replacement string

Here are my attempts to replace a b character with a newline using sed while running bash

$> echo 'abc' | sed 's/b/\n/'
anc

no, that's not it

$> echo 'abc' | sed 's/b/\\n/'
a\nc

no, that's not it either. The output I want is

a
c

HELP!

Looks like you are on BSD or Solaris. Try this:

[jaypal:~/Temp] echo 'abc' | sed 's/b/\ 
> /'
a
c

Add a black slash and hit enter and complete your sed statement.

$ echo 'abc' | sed 's/b/\'$'\n''/'
a
c

In Bash, $'\n' expands to a single quoted newline character (see "QUOTING" section of man bash ). The three strings are concatenated before being passed into sed as an argument. Sed requires that the newline character be escaped, hence the first backslash in the code I pasted.

You didn't say you want to globally replace all b . If yes, you want tr instead:

$ echo abcbd | tr b $'\n'
a
c
d

Works for me on Solaris 5.8 and bash 2.03

In a multiline file I had to pipe through tr on both sides of sed, like so:

echo "$FILE_CONTENTS" | \ tr '\n' ¥ | tr ' ' ∑ | mySedFunction $1 | tr ¥ '\n' | tr ∑ ' '

See unix likes to strip out newlines and extra leading spaces and all sorts of things, because I guess that seemed like the thing to do at the time when it was made back in the 1900s. Anyway, this method I show above solves the problem 100%. Wish I would have seen someone post this somewhere because it would have saved me about three hours of my life.

echo 'abc' | sed 's/b/\'\n'/' 

你在\n周围缺少''

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