How can I search and replace text that contains / with sed?

I currently use the following command which doesn't work

sed -i "s/queue_directory = /var/spool/postfix-secondary/queue_directory = /var/spool/postfix-$newnumber/g" /etc/postfix-$newnumber/main.cf
  • 3
    backslash escape it when not a delimiter or swap delimiters: s|queue_directory = /var/spool.*|newnumber|. – mikeserv Jul 2 '15 at 22:27
  • What's the full command for that? – Teddy291 Jul 2 '15 at 22:33
  • @WhimsicalWombat - it just feels... cheap. But you're welcome to, and guaranteed at least one upvote if you ping me when through. Teddy - wherever you do s/// the stuff between those comprise the address and replace fields. If the stuff contains / then you just have to use something else like s|||, or backslash escape the stuff within like s/\///. It works for regular addresses too, but those always require a backslash when not / like: sed '\|^/|s/.//' which will remove a / if it occurs at the head of a line. And so the full command is your command where s/// is s||| instead. – mikeserv Jul 2 '15 at 22:42
  • For more info about regex visit gnu.org/software/sed/manual/html_node/Regular-Expressions.html and to try what you want with a little explanation visit regexr.com – tachomi Jul 2 '15 at 23:20

One approach is to pick a different delimiter besides /. For example, using |:

sed -ie "s|queue_directory = /var/spool/postfix-secondary|queue_directory = /var/spool/postfix-$newnumber|g" /etc/postfix-$newnumber/main.cf

Another approach is to backslash-escape your other slashes:

sed -ie "s/queue_directory = \/var\/spool\/postfix-secondary/queue_directory = \/var\/spool\/postfix-$newnumber/g" /etc/postfix-$newnumber/main.cf

Two more suggestions for your particular usage. First, I don't think you need the g flag, unless you anticipate the substitution appearing multiple times in the same line. Second, if you are just trying to change a directive, you could potentially just change it no matter what the previous value. For example:

sed -ie "s|^queue_directory =.*|queue_directory = /var/spool/postfix-$newnumber|" /etc/postfix-$newnumber/main.cf

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.