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
worked fine on El Captitan with
()
supportIn vi on Red Hat, I was able to insert carriage returns using just the \r character. I believe this internally executes 'ex' instead of 'sed', but it's similar, and vi can be another way to do bulk edits such as code patches. For example. I am surrounding a search term with an if statement that insists on carriage returns after the braces:
Note that I also had it insert some tabs to make things align better.
Hmm, just escaped newlines seem to work in more recent versions of
sed
(I have GNU sed 4.2.1),You can use perl one-liners much like you do with sed, with the advantage of full perl regular expression support (which is much more powerful than what you get with sed). There is also very little variation across *nix platforms - perl is generally perl. So you can stop worrying about how to make your particular system's version of sed do what you want.
In this case, you can do
-pe
puts perl into a "execute and print" loop, much like sed's normal mode of operation.'
quotes everything else so the shell won't interfere()
surrounding the regex is a grouping operator.$1
on the right side of the substitution prints out whatever was matched inside these parens.Finally,
\n
is a newline.Regardless of whether you are using parentheses as a grouping operator, you have to escape any parentheses you are trying to match. So a regex to match the pattern you list above would be something like
\(
or\)
matches a literal paren, and\d
matches a digit.Better:
I imagine you can figure out what the numbers in braces are doing.
Additionally, you can use delimiters other than / for your regex. So if you need to match / you won't need to escape it. Either of the below is equivalent to the regex at the beginning of my answer. In theory you can substitute any character for the standard /'s.
Bonus tip - if you have the pcre package installed, it comes with
pcregrep
, which uses full perl-compatible regexes.This works in MAC for me
Dono whether its perfect one...
On my mac, the following inserts a single 'n' instead of newline:
This replaces with newline: