【问题标题】:ignoring variable containing \ and multiple spaces usnig sed command使用 sed 命令忽略包含 \ 和多个空格的变量
【发布时间】:2016-10-21 12:32:49
【问题描述】:

我有两个变量,

first= new pool ser/@10.25.89.322 
second=ESX_10.2.3.4@10.52.33.21

我想用新池 ser/@10.25.89.322 替换 ESX_10.2.3.4@10.52.33.21 并且还想删除新单词前的空格。

我试过了,

sed -i -e "s/${second}/"${first//\\/\\\\}"/g"

和

sed -i -e "s/${second}/"${first//\\[ ]*/\\\\}"/g"
sed -i -e "s/${second}/"${first//\\ */ *\\\\}"/g"

我不想删除空格,只想按原样替换(“new”之前的空格除外)。

【问题讨论】:

  • 我喜欢 ,sed -i -e "s/${second}/"${first//\\/\\\\}"/g" 和 sed -i -e "s/${second}/"${first//\[ ]*/\\\\}"/g" 也 sed -i -e "s/${second}/"${first//\\ */ *\\\\}"/g" 但没用。

标签: linux shell replace sed


【解决方案1】:

试试这个:

sed -i "/${second}/ {s:${second}:${first//\\/\\\\}:g ; s/ new /new /}"

它正在删除替换后行中第一次出现new的space。

另外,在下面的测试中,添加了双引号:

$ first=" new pool ser/@10.25.89.322" 
$ second=ESX_10.2.3.4@10.52.33.21
$ sed -i "/${second}/ {s:${second}:${first//\\/\\\\}:g ; s/ new /new /}" mytestfile.txt

【讨论】:

  • @Rishi 超级!那么考虑正式接受这个答案。
猜你喜欢
  • 1970-01-01
  • 2019-04-05
  • 2018-02-01
  • 1970-01-01
  • 2020-04-20
  • 2021-09-15
  • 2017-10-04
  • 2020-06-01
  • 2017-12-03
相关资源
最近更新 更多