Sed – find and replace text containing “/”

sed

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

Best Answer

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
Related Question