2

I am trying to replace the text within a file with the contents of a variable $ourpath, so that a directory path is replaced.

    sed -e "s/__REPLACE_THIS_PATH__/${ourpath}/" com.plex.plexconnect_daemon.bash.plist  > com.plex.plexconnect_daemon.bash.plist

but when i run this, it just deletes the contents of the file, or is overwriting it with a zero length file.

any thoughts?

2
  • Variables are not expanded inside single quotes, only double quotes. This is basic shell scripting. Commented Nov 14, 2013 at 6:25
  • my bad, i had double quotes in my original script. i just saw something on a web page which had single which i tried. i forgot to change back. question is now updated. thanks for the headsup. but it still doesn't work with the double quotes. Commented Nov 14, 2013 at 6:33

1 Answer 1

2

You can't redirect output to the input file. When the redirection happens, the file is truncated, so there's nothing to read from. Either write to a different file and then rename it, or use the -i option to sed:

sed -i.bak -e "s/__REPLACE_THIS_PATH__/${ourpath}/" com.plex.plexconnect_daemon.bash.plist

This will add the .bak suffix to the original file and put the result in a new file with the original name.

Sign up to request clarification or add additional context in comments.

4 Comments

could i write the new file to a different folder? in which case, how would that look? my code below doesn't seem to work sed -i -e "s/__REPLACE_THIS_PATH__/${ourpath}/" ./com.plex.plexconnect_daemon.bash.plist > /Library/LaunchDaemons/com.plex.plexconnect_daemon.bash.plist
If you're using -i you don't need the redirect: sed -i -e "s/__REPLACE_THIS_PATH__/${ourpath}/" ./com.plex.plexconnect_daemon.bash.plist
what if i wanted to have the updated file located in a different folder, leaving the original untouched?
Then you do it like in your original code, with redirection. The only special case is when you want to overwrite the original file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.