tags:

views:

1374

answers:

3

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

A: 

In sed, you can't add newlines in the output stream easily. You need to use a continuation line, which is awkward, but it works:

$ sed 's/regexp/\
&/'

Example:

$ echo foo | sed 's/.*/\
&/'

foo

See here for details. If you want something slightly less awkward you could try using perl -pe with match groups instead of sed:

$ echo foo | perl -pe 's/(.*)/\n$1/'

foo

$1 refers to the first matched group in the regular expression, where groups are in parentheses.

tgamblin
A: 

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'
Steve B.
Actually this doesn't work for inserting a newline. Try it.
tgamblin
Just did: testfile contents="ABC ABC ABC". Ran "sed 's/\(ABC\)/\n\1/g' testfile, got the newlines. Experiment with the escapes, try to add 1 thing at a time to your pattern, e.g. make sure you're matching the pattern, then check the group matching, then add the newline checking.
Steve B.
I just tried exactly that and got "nABC nABC nABC'. Are you using some other version of sed?
tgamblin
+3  A: 

I tried some of the examples but they didn't seem to work. However, I found a solution. I simply had to switch the position of & and \n.

Thus

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

I'd like to thank you guys anyways though.

Dennis
I'm not sure this works in all versions of sed. I tried this on my Mac and the \n just gets output as 'n'
tgamblin