无需尝试即可创建多态的bash.更换sed [英] Create polymorphic bash without die trying. Sed replacing

查看:48
本文介绍了无需尝试即可创建多态的bash.更换sed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个bash脚本,该脚本需要一处修改自身,以使该脚本的更改(仅一行)持久化.

I'm creating a bash script which in one point needs to modify itself in order to make persistent a change (only one line) of the script needs to change.

我知道 sed -i 是我要做的.问题是我的sed命令正在替换存储命令的行,而不是我想要的行.所以我想我需要在替换时包括一个排除项.让我们检查代码段内容:

I know sed -i is what I need to do this. The problem is my sed command is replacing the line where the command is stored instead of the line I want. So I guess I need to include an exclusion while replacing. Let's check the snippet code stuff:

#!/bin/bash

echo "blah,blah,blah"
echo "more code here, not matters"
sed -i "s/#Awesome line to be replaced/#New line here/" "/path/to/my/script" 2> /dev/null

#Awesome line to be replaced
echo "blah,blah,blah, more code blah"

这里的问题是被替换的行不是仅具有 #Awesome行要替换的行.它将替换为sed命令所在的行.

The problem here is the replaced line is not the line with only #Awesome line to be replaced. It is replaced the line where the sed command is.

这是一个简化的示例,但是脚本是多态的,也许行号发生了变化,因此它不能基于行号.而且会有更多这样的sed命令...所以我认为最好在sed命令行中包含一些文本,以便将其用作排除模式,是的!那段文字是/dev/null ,它总是会在sed命令行中出现,而永远不会出现在我要替换的行中.

This is a reduced example but the script is polymorphic and maybe the line numbers change, so it can't be based on line numbers. And there will be more sed commands like this... so I thought It could be nice to have some piece of text which always could be in the sed command lines in order to use it as excluding pattern, and yeah! that piece of text is /dev/null which always will be in sed command lines and never in the line which I want to replace.

如何使用 sed -i 实现此目的?预先感谢.

How can achieve this using sed -i? Thanks in advance.

编辑由于多态性,忘记说外观顺序(偏移)也不能使用.

EDIT Forgot to say the order of appearance (offset) can't be used neither because of the polymorphic thing.

EDIT2 #Awesome行要替换的之前的开头字符不能使用,因为它们也可能会发生变化.对不起,谁已经基于此回答.考虑所有可能性,编写多态代码段很复杂.

EDIT2 Beginning chars before #Awesome line to be replaced can't be used because they could change too. Sorry for who already answered based on this. Is complicated to write a polymorphic snippet considering all the possibilities.

推荐答案

此hack可以起作用:

This hack can work:

sed -i "s/#[A]wesome line to be replaced/#New line here/" "/path/to/my/script" 2> /dev/null

我认为这是不言自明的,为什么它与 sed 行本身不匹配.

I think it is self-explanatory, why it will not match the sed line itself.

这篇关于无需尝试即可创建多态的bash.更换sed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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