使用 sed 替换字符串
Replace a string using sed
我想使用 sed
将字符串 ip_ttl="1"
替换为 ip_ttl="2"
。
我试过 sed -i "s/ip_ttl="1"/ip_ttl="2"/g"
- 但它不起作用。
请帮忙!
将您的 sed 代码放在单引号内,因为您的代码已经包含双引号。
sed -i 's/ip_ttl="1"/ip_ttl="2"/g' file
如果您将代码放在两个双引号内,一旦到达另一个双引号,sed 就会终止程序。所以 "
在 1
之前,它会认为结束并终止程序。
更新:
如果数字总是变化,那么最好定义匹配任何数字的模式。
sed -i 's/ip_ttl="[0-9]\+"/ip_ttl="2"/g' file
或者您可以转义引号
sed -i "s/ip_ttl=\"1\"/ip_ttl=\"2\"/g" file
有时这很有用,因为您要选择的字符串中同时包含单引号和双引号。
如果您在模式中使用引号,请在模式中转义双引号:
sed -i "s/ip_ttl=\"1\"/ip_ttl=\"2\"/g"
或用单引号将整个模式括起来:
sed -i 's/ip_ttl="1"/ip_ttl="2"/g'
我想使用 sed
将字符串 ip_ttl="1"
替换为 ip_ttl="2"
。
我试过 sed -i "s/ip_ttl="1"/ip_ttl="2"/g"
- 但它不起作用。
请帮忙!
将您的 sed 代码放在单引号内,因为您的代码已经包含双引号。
sed -i 's/ip_ttl="1"/ip_ttl="2"/g' file
如果您将代码放在两个双引号内,一旦到达另一个双引号,sed 就会终止程序。所以 "
在 1
之前,它会认为结束并终止程序。
更新:
如果数字总是变化,那么最好定义匹配任何数字的模式。
sed -i 's/ip_ttl="[0-9]\+"/ip_ttl="2"/g' file
或者您可以转义引号
sed -i "s/ip_ttl=\"1\"/ip_ttl=\"2\"/g" file
有时这很有用,因为您要选择的字符串中同时包含单引号和双引号。
如果您在模式中使用引号,请在模式中转义双引号:
sed -i "s/ip_ttl=\"1\"/ip_ttl=\"2\"/g"
或用单引号将整个模式括起来:
sed -i 's/ip_ttl="1"/ip_ttl="2"/g'