Bash脚本:在文件的特定行的最后一个字符处追加文本。

时间:2022-08-25 00:29:24

I am trying to append a variable at the last character of a specific line of a file from a bash script.

我试图在bash脚本中某个文件特定行的最后一个字符处附加一个变量。

The file is called myfile.txt and what I want to do is to append the contents of a variable named VERSION right after the last character of the line of the file that contains the unique string MYVERSION.

该文件称为myfile。txt和我想做的是在包含唯一字符串MYVERSION的文件行的最后一个字符后面追加一个名为VERSION的变量的内容。

That is, if in this line there is the following:

也就是说,如果这一行有以下内容:

MYVERSION=0.1

and VERSION="-custom_P1" then, I want to have the following:

而VERSION="-custom_P1"我想要的是:

MYVERSION=0.1-custom_P1

Thank you all for the help.

谢谢大家的帮助。

2 个解决方案

#1


3  

Try this:

试试这个:

sed -i "/^MYVERSION=/ s/\$/$VERSION/" myfile.txt

The idea is that it finds a line that starts with MYVERSION= and then replaces the end of that line with the contents of the $VERSION environment variable.

其思想是找到以MYVERSION=开头的行,然后用$VERSION环境变量的内容替换行尾。

Edit: originally I wasn't sure if the first $ needed to be escaped, but @sehe's comment and its upvoters convinced me that it does.

编辑:起初我不确定是否需要转义,但是@sehe的评论和它的支持者说服了我。

#2


0  

Try

试一试

sed -e "s/^MYVERSION=/MYVERSION=.*$/&${VERSION}/g" < myfile.txt

The command appends the value of VERSION to the line with 'MYVERSION='

该命令将VERSION值附加到带有'MYVERSION='的行中

#1


3  

Try this:

试试这个:

sed -i "/^MYVERSION=/ s/\$/$VERSION/" myfile.txt

The idea is that it finds a line that starts with MYVERSION= and then replaces the end of that line with the contents of the $VERSION environment variable.

其思想是找到以MYVERSION=开头的行,然后用$VERSION环境变量的内容替换行尾。

Edit: originally I wasn't sure if the first $ needed to be escaped, but @sehe's comment and its upvoters convinced me that it does.

编辑:起初我不确定是否需要转义,但是@sehe的评论和它的支持者说服了我。

#2


0  

Try

试一试

sed -e "s/^MYVERSION=/MYVERSION=.*$/&${VERSION}/g" < myfile.txt

The command appends the value of VERSION to the line with 'MYVERSION='

该命令将VERSION值附加到带有'MYVERSION='的行中