1

I have a script with hundreds of lines and while my search and replace command works and removes it in multiple locations.

The text to replace is located in another file and my search and replace works perfectly but unfortunately I want only the first instance of the block text to be replaced.

ORIGINAL_FILE TEXT_FILE NEW_FILE

Replace all text between RECOMMENDED and STATIC with content from TEXT_FILE

sed -n -e "1,/RECOMMENDED/ p" -e "/STATIC/,$ p" -e "/RECOMMENDED/ r $TEXT_FILE" $ORIGINAL_FILE >$NEW_FILE

As I say this works but there are multiple locations where RECOMMENDED and STATIC are available and I want to only change the first instance.

Any help is greatly appreciated

1

If you do:

sed -n -e '1,/RECOMMENDED/ p' \
       -e '/STATIC/,$ {p;d;}' \
       -e "/RECOMMENDED/ r $TEXT_FILE" < "$ORIGINAL_FILE" > "$NEW_FILE"

Then the /RECOMMENDED/ won't match after lines matching /STATIC/ since we delete them after printing.

  • Hello Stephane that kinda worked also but for some reason it added the content of the $TEXT_FILE 4 times in the $NEW_FILE and I believe it's because the RECOMMENDED .... STATIC exists in multiple locations in the $ORIGINAL_FILE file. – gcclinux Aug 18 '17 at 8:56
  • @gcclinux, with that code, that would only happen in there were several occurrences of RECOMMENDED before the first STATIC – Stéphane Chazelas Aug 18 '17 at 9:51
  • Hi Stéphane thank you for your advise and that may be the issue the script contains multiple blocks of code containing RECOMMENDED & STATIC and therefore I wish to only replace the 1st instance and ignore the subsequence ones, if you have any idea that would be great, i could provide code snips of the script if that helps or send you the entire script if you could help. – gcclinux Aug 18 '17 at 12:12
  • @gcclinux, please update your question to give a minimal sample input to work on. One for which this answer is currently not satisfactory. Clarifying if those blocks can be nested or not, etc. – Stéphane Chazelas Aug 18 '17 at 12:13
  • @ Stéphane I've modified what I am searching for and the script update works as you described. I take a snip from what I want to keep in the old script, replace the snip in to the new script as you described and it workers perfectly.. Thank you – gcclinux Aug 18 '17 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.