escaping newlines in sed replacement string

2019-01-17 20:21发布

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!

5条回答
相关推荐>>
2楼-- · 2019-01-17 21:01

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.

查看更多
劫难
3楼-- · 2019-01-17 21:12

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.

查看更多
放我归山
4楼-- · 2019-01-17 21:15

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

查看更多
我只想做你的唯一
5楼-- · 2019-01-17 21:20
echo 'abc' | sed 's/b/\'\n'/' 

you are missing '' around \n

查看更多
趁早两清
6楼-- · 2019-01-17 21:22
$ 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.

查看更多
登录 后发表回答