2

I'm looking to write a script/command, that'll take inputFile1, look for a specific start and end string in it, and replace all the text in between them with the full contents of inputFile2.

Ideally, but not mandatory, this should work without a need to escape special characters, so I can put the strings in variables that get called by the script (that way I could easily reuse it multiple times).

As an example, I have file inputYes.txt with contents:

DummyOne
Start
That
What
Yes
End
DummyTwo

And inputNo.txt with contents:

This
Why
Not

And I want the script to search inputYes.txt for the strings Start and End, and replace all the text in between with the contents of inputNo.txt, and write to the file.

So after running it, inputYes.txt should read

DummyOne
Start
This
Why
Not
End
DummyTwo
Tomilov Anatoliy
  • 15,657
  • 10
  • 64
  • 169
user137369
  • 5,219
  • 5
  • 31
  • 54
  • Possible duplicate of a question I already answered.. http://stackoverflow.com/questions/12443122/using-sed-to-print-between-two-patterns/12443133#12443133 – Piotr Wadas Sep 17 '12 at 22:26

1 Answers1

1
sed '/end_string/rinputFile2
/start_string/,/end_string/d' inputFile1
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • I can't exactly tell what this is doing, but I can tell it's not working, it seems to simply be echoing the contents of inputFile1. And I need it to write to the file, not just print on the terminal. I'll update the question with more details. – user137369 Sep 17 '12 at 22:48
  • Any text between the lines which match `start_string` and `end_string` should be replaced with the contents of `inputFile2`. Redirecting the output to a file is trivial. – William Pursell Sep 17 '12 at 22:50
  • It's not doing anything on my system. I'm running OSX, perhaps `sed` is different? – user137369 Sep 17 '12 at 22:58
  • According to my post edit, I'm running `sed '/End/rinputNo.txt/Start/,/End/d' inputYes.txt`, and it's simply printing the contents of _inputYes.txt_. – user137369 Sep 17 '12 at 23:02
  • Newlines are significant. The command must have a literal newline after the filename. Your command is looking for a file named `inputNo.txt/Start/,/End/d` – William Pursell Sep 17 '12 at 23:20
  • I thought the line had been truncated, didn't realize it was on purpose, thank you very much, it works. Extra tip, can I tell it to add a newline at the end of the substitution? – user137369 Sep 18 '12 at 10:48
  • The easiest way would be to add an extra newline to the end of `inputFile1`. – William Pursell Sep 18 '12 at 16:08