2

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.

jww
  • 97,681
  • 90
  • 411
  • 885
hdl
  • 1,028
  • 1
  • 9
  • 23

2 Answers2

1

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.

Community
  • 1
  • 1
dummy
  • 4,256
  • 3
  • 25
  • 36
  • My problem is that PUT_BEFORE is several lines long and contains lots of special characters that would need to be escaped, that's why I want to read it from a file it is already in. I think I could create a temp file containing only these lines and read it, but I'd like to know if reading ranges is possible with GNU sed. – hdl Sep 24 '15 at 14:21
  • Thanks, that's useful but I've just found an answer that spares the additional cost of calling `cat` or another instance of `sed`. I will post it below but however it does not solve the problem of reading *specific* lines of a file yet. – hdl Sep 24 '15 at 14:59
0

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.

Community
  • 1
  • 1
hdl
  • 1,028
  • 1
  • 9
  • 23