Command to Insert Lines Before First Match

Command to insert lines before first match

For lines consisting of "testing" exactly:

sed '0,/^testing$/s/^testing$/tested\n&/' file

For lines containing "testing":

sed '0,/.*testing.*/s/.*testing.*/tested\n&/' file

For Lines Starting with "testing"

sed '0,/^testing.*/s/^testing.*/tested\n&/' file

For lines ending with "testing":

sed '0,/.*testing$/s/.*testing$/tested\n&/' file

To update the content of the file with the result add "-i", example:

sed -i '0,/testing/s/testing/tested\n&/' file

sed to insert on first match only

If you want one with sed*:

sed '0,/Matched Keyword/s//Matched Keyword\nNew Inserted Line/' myfile.txt

*only works with GNU sed

How to insert a line before the FIRST and LAST matching pattern using sed

Example how to do it in Perl

perl -nE'/Surname/&&($n++||say"Name")||($n=0);/Age/&&($g=1)||($g--&&say"Gender");print}{say"Gender"if$g'

And another way

perl -nE'/Surname/&&say("Name")..!/Surname/;/Age/&&($g=1)||($g--&&say"Gender");print}{say"Gender"if$g'

Adding a new line before a pattern

The command to insert before is i

sed  -i '/pattern/iNew Text' input_file

This command insert what you want before the line that matches your pattern, but if you want to insert something before the match itself, use a replacement with a capture group.

How to insert a newline in front of a pattern?

Some of the other answers didn't work for my version of sed.
Switching the position of & and \n did work.

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

Edit: This doesn't seem to work on OS X, unless you install gnu-sed.

Insert blank line before line matching pattern in sed

This should work perfectly. I tested it on Ubuntu with no issues.

number=3
sed $number'i\\' test.txt

Regards!

How to use awk to insert multiple lines after first match of a pattern, in multiple files

Assuming the text to insert is in a file called insert:

sed -e '0,/<properties>/{/<properties>/r insert' -e '}' config.xml

The r command reads a file and appends it after the current line; the

0,/pattern/{/pattern/r filename}

makes sure that only the first instance of pattern gets the text appended. Because the command has to end after the filename read by r, it has to be split into two parts using -e.

To edit the files in-place, use sed -i (for GNU sed).

To do this for multiple files, you could use find:

find jobs -name 'config.xml' \
-exec sed -i -e '0,/<properties>/{/<properties>/r insert' -e '}' {} +

This requires that the insert file is in the directory from which you run this command.


Your commands seemed almost correct, except that you didn't nest a second address into your range to make sure the appending happened just once.



Related Topics



Leave a reply



Submit