How to insert a newline in front of a pattern?

2019-01-04 17:59发布

Not how to insert a newline before a line. This is asking how to insert a newline before a pattern within a line.

For example,

sed 's/regexp/&\n/g'

will insert a newline behind the regexp pattern.

How can I do the same but in front of the pattern?

Here is an example input file

somevariable (012)345-6789

Should become

somevariable
(012)345-6789

标签: shell sed
16条回答
乱世女痞
2楼-- · 2019-01-04 18:42

To insert a newline to output stream on Linux, I used:

sed -i "s/def/abc\\\ndef/" file1

Where file1 was:

def

Before the sed in-place replacement, and:

abc
def

After the sed in-place replacement. Please note the use of \\\n. If the patterns have a " inside it, escape using \".

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-04 18:46
sed -e 's/regexp/\0\n/g'

\0 is the null, so your expression is replaced with null (nothing) and then...
\n is the new line

On some flavors of Unix doesn't work, but I think it's the solution at your problem.

echo "Hello" | sed -e 's/Hello/\0\ntmow/g'
Hello
tmow
查看更多
We Are One
4楼-- · 2019-01-04 18:48

in sed you can reference groups in your pattern with "\1", "\2", .... so if the pattern you're looking for is "PATTERN", and you want to insert "BEFORE" in front of it, you can use, sans escaping

sed 's/(PATTERN)/BEFORE\1/g'

i.e.

  sed 's/\(PATTERN\)/BEFORE\1/g'
查看更多
Root(大扎)
5楼-- · 2019-01-04 18:53

After reading all the answers to this question, it still took me many attempts to get the correct syntax to the following example script:

#!/bin/bash
# script: add_domain
# using fixed values instead of command line parameters $1, $2
# to show typical variable values in this example
ipaddr="127.0.0.1"
domain="example.com"
# no need to escape $ipaddr and $domain values if we use separate quotes.
sudo sed -i '$a \\n'"$ipaddr www.$domain $domain" /etc/hosts

The script appends a newline \n followed by another line of text to the end of a file using a single sed command.

查看更多
登录 后发表回答