-->

Bash script: Appending text at the last character

2020-03-28 01:34发布

问题:

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

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.

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

MYVERSION=0.1

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

MYVERSION=0.1-custom_P1

Thank you all for the help.

回答1:

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.

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.



回答2:

Try

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

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