hdl
hdl

Reputation: 1038

Insert specific lines from file before first occurrence of pattern using Sed

I want to insert a range of lines from a file, say something like 210,221r before the first occurrence of a pattern in a bunch of other files.

As I am clearly not a GNU sed expert, I cannot figure how to do this.

I tried

sed '0,/pattern/{210,221r file
}' bunch_of_files

But apparently file is read from line 210 to EOF.

Upvotes: 2

Views: 1012

Answers (2)

hdl
hdl

Reputation: 1038

In https://stackoverflow.com/a/11246712/4328188 CodeGnome gave some "sed black magic" :

In order to insert text before a pattern, you need to swap the pattern space into the hold space before reading in the file. For example:

sed '/pattern/ {
     h
     r file
     g
     N
 }' in

However, to read specific lines from file, one may have to use a two-calls solution similar to dummy's answer. I'd enjoy knowing of a one-call solution if it is possible though.

Upvotes: 0

dummy
dummy

Reputation: 4284

Try this:

sed -r 's/(FIND_ME)/PUT_BEFORE\1/' test.text
  • -r enables extendend regular expressions
  • the string you are looking for ("FIND_ME") is inside parentheses, which creates a capture group
  • \1 puts the captured text into the replacement.

About your second question: You can read the replacement from a file like this*:

sed -r 's/(FIND_ME)/`cat REPLACEMENT.TXT`\1/' test.text

If replace special characters inside REPLACEMENT.TXT beforehand with sed you are golden.

*= this depends on your terminal emulator. It works in bash.

Upvotes: 1

Related Questions