桑达:用字符串变量替换字符串变量 [英] Sed: replace string variable with string variable

查看:200
本文介绍了桑达:用字符串变量替换字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为以太网包含多行文件。我有救这些线路中的一个作为变量叫 old_line 。这个变量的内容是这样的:

  SUBSYSTEM ==网,ACTION ==增加,DRIVERS ==,ATTR {}地址==2R*?:11:89:89:9克:啊,ATTR {}的dev_id ==为0x0,ATTR {类型} ==1,KERNEL ==ETH *,NAME =eth1的

我已经创建了一个名为第二个变量的 NEW_LINE 类似于 old_line ,但在文本一些修改。

我想替换的内容的 old_line NEW_LINE 使用SED的内容。到目前为止,我有以下,但它不工作:

  SED -iS / $ {old_line} / $ {} NEW_LINE / g的以太网


解决方案

您需要逃避你的 oldline ,以便它不包含正则表达式的特殊字符,幸运的是,这是可以做到与sed的。

  old_line = $(回声$ {} old_line| sed的-e的/[]$.*[\\^]/\\\\&安培/克)
SED -i -eS / $ {old_line} / $ {} NEW_LINE / g的以太网

I have a file called ethernet containing multiple lines. I have saved one of these lines as a variable called old_line. The contents of this variable looks like this:

SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="2r:11:89:89:9g:ah", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"

I have created a second variable called new_line that is similar to old_line but with some modifications in the text.

I want to substitute the contents of old_line with the contents of new_line using sed. So far I have the following, but it doesn't work:

sed -i "s/${old_line}/${new_line}/g" ethernet

解决方案

You need to escape your oldline so that it contains no regex special characters, luckily this can be done with sed.

old_line=$(echo "${old_line}" | sed -e 's/[]$.*[\^]/\\&/g' )
sed -i -e "s/${old_line}/${new_line}/g" ethernet

这篇关于桑达:用字符串变量替换字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆