Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

sed

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: '/'
like image 232
DisplayName Avatar asked Dec 11 '22 16:12

DisplayName


1 Answers

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
like image 187
Andreas Louv Avatar answered Jan 05 '23 00:01

Andreas Louv