0

I have this script:

#!/bin/sh
local name="url"
local line='{ "name": "url", "value": "http:\/\/www.example.com\/dir1\/page1" }'

local name2="protocol"
local line2='{ "name": "protocol", "value": "ftp" }'

sed -i "/\<$name2\>/s/.*/$line2/" /mydir/myfile
sed -i "/\<$name\>/s/.*/$line/" /mydir/myfile

myfile contain:

{ "name": "url", "value": "http:\/\/www.example.com\/dir2\/page2" }
{ "name": "url2", "value": "http:\/\/www.example.net/page" }
{ "name": "protocol", "value": "http" }

I detect a problem with / symbol in value field with my sed command. How to fix this error?

2 Answers 2

3

Since your files have / all over the place its better to use an alternate regex delimiter; it is supported by sed.

sed -i "/\<$name2\>/s|.*|$line2|" /mydir/myfile
sed -i "/\<$name\>/s|.*|$line|" /mydir/myfile
Sign up to request clarification or add additional context in comments.

3 Comments

the problem I have other values like ftp|http, in this case how to do it?
You can use: sed -i "/<$name2\>/s~.*~$line2~" /mydir/myfile as I said any character works even control characters.
can I found another command to do this, independently of my value content and name
2

Use a different separator like this:

sed -i "/\<$name2\>/s%.*%$line2%" /mydir/myfile

For example, this is a dump I did just now:

printf "eins x eins\nzwei x zwei\nabc x abc\ndef x def\n" | sed "/abc/s%x%y%"

It prints:

eins x eins
zwei x zwei
abc y abc
def x def

As you can see, just the line containing abc gets modified by the s command.

Instead of the % sign you can use any character which does not appear in the value you want to replace. Keep that in mind. You also can use _ or or ; or a letter, a number, whatever you like. It just mustn't appear in the value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.