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
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:
Example:
See here for details. If you want something slightly less awkward you could try using
perl -pe
with match groups instead of sed:$1
refers to the first matched group in the regular expression, where groups are in parentheses.Some of the other answers didn't work for my version of sed. Switching the position of
&
and\n
did work.Edit: This doesn't seem to work on OS X, unless you install
gnu-sed
.This works in
bash
, tested on Linux and OS X:In general, for
$
followed by a string literal in single quotesbash
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:
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.)
You can also do this with awk, using
-v
to provide the pattern:This checks if a line contains a given pattern. If so, it appends a new line to the beginning of it.
See a basic example:
Note it will affect to all patterns in a line:
In this case, I do not use sed. I use tr.
This takes the comma and replaces it with the carriage return.