Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a newline/linebreak after a line using sed

Tags:

bash

shell

sed

zsh

It took me a while to figure out how to do this, so posting in case anyone else is looking for the same.

like image 687
realityloop Avatar asked Jun 28 '13 10:06

realityloop


People also ask

How do you insert a line break in sed?

You have to use the “-i” option with the “sed” command to insert the new line permanently in the file if the matching pattern exists in the file.

How do I add a new line after a string?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you add a line break in shell script?

The most used newline character If you don't want to use echo repeatedly to create new lines in your shell script, then you can use the \n character. The \n is a newline character for Unix-based systems; it helps to push the commands that come after it onto a new line. An example is below.


2 Answers

For adding a newline after a pattern, you can also say:

sed '/pattern/{G;}' filename 

Quoting GNU sed manual:

G     Append a newline to the contents of the pattern space, and then append the contents of the hold space to that of the pattern space. 

EDIT:

Incidentally, this happens to be covered in sed one liners:

 # insert a blank line below every line which matches "regex"  sed '/regex/G' 
like image 182
devnull Avatar answered Oct 20 '22 14:10

devnull


This sed command:

sed -i '' '/pid = run/ a\ \ ' file.txt 

Finds the line with: pid = run

file.txt before

; Note: the default prefix is /usr/local/var ; Default Value: none ;pid = run/php-fpm.pid  ; Error log file 

and adds a linebreak after that line inside file.txt

file.txt after

; Note: the default prefix is /usr/local/var ; Default Value: none ;pid = run/php-fpm.pid   ; Error log file 

Or if you want to add text and a linebreak:

sed -i '/pid = run/ a\ new line of text\ ' file.txt 

file.txt after

; Note: the default prefix is /usr/local/var ; Default Value: none ;pid = run/php-fpm.pid new line of text  ; Error log file 
like image 24
realityloop Avatar answered Oct 20 '22 14:10

realityloop