DisplayName
DisplayName

Reputation: 222

Getting bad flag in substitute command '/' for sed replacement

I am facing one issue while using replace in my sed command. I've a file named a.txt, I want to replace a single line with some other line but I am getting above mentioned error.

Code I want to replace:

DOMAIN_LOCAL = "http://127.0.0.1:3000";

I want it to replace with any other ip lets say something like below:-

DOMAIN_LOCAL = "http://127.1.1.2:3000";

What I've tried:-

ip=http://127.1.1.2:3000
sed "s/DOMAIN_LOCAL = .*$/DOMAIN_LOCAL = "$ip";/g" a.txt

But it is giving me following error. Can somebody help here.

sed: 1: "s/DOMAIN_LOCAL = .*$/DO ...": bad flag in substitute command: '/'

Upvotes: 6

Views: 13636

Answers (3)

Be Live
Be Live

Reputation: 221

use # replace / to avoid this issue $ sed 's#find#replace#' file

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47099

You will need to use another delimiter. And escape the $ or use single quotes:

% ip="http://127.1.1.2:3000"
% sed 's~DOMAIN_LOCAL = .*$~DOMAIN_LOCAL = "'"$ip"'";~' a.txt
DOMAIN_LOCAL = http://127.1.1.2:3000;

When you use / as a delimiter in the substitute command it will be terminated at the first slash in http://:

sed 's/DOMAIN_LOCAL = .*$/DOMAIN_LOCAL = http://127.1.1.2:3000;/'
#                                             ^ here

Breakdown:

sed 's~DOMAIN_LOCAL = .*$~DOMAIN_LOCAL = "'"$ip"'";~' a.txt
#   │                                    ││└ Use double quotes to avoid word splitting and
#   │                                    ││  globbing on $ip
#   │                                    │└ Exit single quotes
#   │                                    └ Literal double quotes
#   └ Using single quotes to avoid having to escape special characters

Upvotes: 13

Darwin.Lau
Darwin.Lau

Reputation: 226

You may need another delimiter instead of "/", for example "%".It worked for me.

Upvotes: 3

Related Questions