Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using sed to insert file content into a file BEFORE a pattern

Tags:

regex

sed

I'm new to sed, I'm trying to insert the content of a BFile into the file AFile, BEFORE a pattern (in AFile)

Hereafter's what I've tried :

sed -i '/blah Blah/r BFile' AFile : it's inserting the content of BFile AFTER the pattern in AFile.

sed -i '/blah Blah/i BFile' AFile : it's inserting the string 'BFile' BEFORE the pattern in AFile.

... hmmm

I'm conscious it's because of a wrong comprehension of regexp or sed : I can't understand how the /i and /r work here... I can't find any help in sed --help

Anyone understanding my point ?

Regards,

Stan

like image 558
St3an Avatar asked Oct 01 '14 12:10

St3an


2 Answers

This might work for you (GNU sed):

sed $'/blah Blah/{e cat BFile\n}' AFile

or:

sed -e 'N;/\n.*blah Blah/{r BFile' -e '};P;D' AFile

or as Alek pointed out:

sed '/blah Blah/e cat BFile' AFile
like image 137
potong Avatar answered Nov 15 '22 20:11

potong


sed's r command does not change the pattern space. The file's content is printed at the end of the current cycle or when the next input line is read (info sed), therefore the N in the following command

sed '/blah Blah/ {
r Bfile
N
}' Afile
like image 33
FrankL Avatar answered Nov 15 '22 18:11

FrankL