1

I currently have a sed command that matches a specific phrase in a file, and replaces all lines of that file with the full text of a different file. This works for the phrase "### REPLACE EVERYTHING AFTER THIS LINE ###"

sed -n -e '1,/^### REPLACE EVERYTHING AFTER THIS LINE ###$/{ p; d; }' \
       -e 'r replacement_file.txt' \
       -e 'q' original_file.txt > original_file.txt.new &&
mv original_file.txt.new original_file.txt

This command works for text files, but in needing to replace files with javascript style comments, I've hit a bit of a snag. The new line/phrase I'm trying to match is now the following (and note I want to match this specific comment, not all comments that start with the double forward slash):

//REPLACE AFTER THIS

I've hit a snag as I'm currently failing to escape the double forward slash. I've tried escaping the two characters with a backslash, but that did not work. My current (non-working) command is the following:

sed -n -e ‘1,/^\/\/REPLACE AFTER THIS$/{ p; d; }’\ 
       -e 'r replacement_file.txt' \
       -e 'q' original_file.txt > original_file.txt.new && mv original_file.txt.new original_file.txt

Thanks in advance.

2
  • 1
    you can use other delimiters than slashes by preceding the startimg one with a backslash: sed -n '\|^//|p'
    – pizdelect
    Mar 31, 2020 at 0:22
  • Once you fix the quotes, \/\/ should work - if it doesn't, try making the match less specific e.g. removing the $ anchor in case there is trailing whitespace Mar 31, 2020 at 1:01

1 Answer 1

1

Thanks to those who commented, in addition to fixing the non-ASCII quote, here is the working command:

sed -n -e '1,\|^//REPLACE TEST$|{ p; d; }' \
    -e 'r replacement_file.txt' \
    -e 'q' original_file.txt > original_file.txt.new && mv original_file.txt.new original_file.txt

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.