Create polymorphic bash without die trying. Sed re

2019-09-07 02:21发布

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.

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"

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.

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.

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 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.

标签: bash replace sed
2条回答
我想做一个坏孩纸
2楼-- · 2019-09-07 03:20

This hack can work:

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

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

查看更多
仙女界的扛把子
3楼-- · 2019-09-07 03:22

Anchor your expression by starting your sed line with :

sed -i "s/^$'\t'*#Awesome (rest of command goes here)

This will make sure sed only matches if the text found is at the beginning of the line with zero or more tabs, and will not match the line with the actual sed command.

查看更多
登录 后发表回答