简体   繁体   English

使用sed替换字符串

[英]Replace a string using sed

I want to replace a string ip_ttl="1" with ip_ttl="2" using sed . 我想使用sed将字符串ip_ttl="1"替换为ip_ttl="2"

I've tried sed -i "s/ip_ttl="1"/ip_ttl="2"/g" - but its not working. 我试过sed -i "s/ip_ttl="1"/ip_ttl="2"/g" -但它不起作用。

Please help! 请帮忙!

Put your sed code inside single quotes, because your code already contains double quotes. 将sed代码放在单引号中,因为您的代码已经包含双引号。

sed -i 's/ip_ttl="1"/ip_ttl="2"/g' file

If you put your code within two double quotes, sed would terminate the program once another double quote was reached. 如果将代码放在两个双引号中,则sed将在到达另一个双引号后终止程序。 So " before 1 was reached, it would consider as the end and terminates the program. 因此, "在到达1之前,它将视为结束并终止程序。

Update: 更新:

If the number always changes then it's better to define the pattern which matches any number. 如果数字总是变化,那么最好定义与任何数字匹配的模式。

sed -i 's/ip_ttl="[0-9]\+"/ip_ttl="2"/g' file

If you are using quotation marks in your pattern either escape double quotes in pattern: 如果在模式中使用引号,则可以在模式中使用双引号引起来:

sed -i "s/ip_ttl=\"1\"/ip_ttl=\"2\"/g"

or enclose whole pattern in single quotes: 或将整个模式用单引号引起来:

sed -i 's/ip_ttl="1"/ip_ttl="2"/g'

Alternatively you can escape the quotation marks 或者,您可以转义引号

sed -i "s/ip_ttl=\"1\"/ip_ttl=\"2\"/g" file

Sometimes that's useful because you have both single and double quotes in a string you're selecting for. 有时这很有用,因为在要选择的字符串中同时包含单引号和双引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM