How to insert a newline in front of a pattern?

Dennis picture Dennis · Apr 6, 2009 · Viewed 275.2k times · Source

How to insert a newline before a pattern within a line?

For example, this will insert a newline behind the regex pattern.

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

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

Given this sample input file, the pattern to match on is the phone number.

some text (012)345-6789

Should become

some text
(012)345-6789

Answer

mojuba picture mojuba · Jun 22, 2012

This works in bash and zsh, tested on Linux and OS X:

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

In general, for $ followed by a string literal in single quotes bash performs C-style backslash substitution, e.g. $'\t' is translated to a literal tab. Plus, sed wants your newline literal to be escaped with a backslash, hence the \ before $. And finally, the dollar sign itself shouldn't be quoted so that it's interpreted by the shell, therefore we close the quote before the $ and then open it again.

Edit: As suggested in the comments by @mklement0, this works as well:

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

What happens here is: the entire sed command is now a C-style string, which means the backslash that sed requires to be placed before the new line literal should now be escaped with another backslash. Though more readable, in this case you won't be able to do shell string substitutions (without making it ugly again.)