[英]replace line in file with sed command
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: myfile包含:
{ "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. 我用sed命令在值字段中检测到/
符号有问题。 How to fix this error? 如何解决这个错误?
Since your files have /
all over the place its better to use an alternate regex delimiter ; 由于您的文件有/
所有的地方它能够更好地使用替代正则表达式分隔符 ; it is supported by sed. 它由sed支持。
sed -i "/\<$name2\>/s|.*|$line2|" /mydir/myfile
sed -i "/\<$name\>/s|.*|$line|" /mydir/myfile
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. 如您所见,仅包含abc
的行被s
命令修改。
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. 它只是不能出现在值中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.