limp
limp

Reputation: 909

Bash script: Appending text at the last character of specific line of a file

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.

Upvotes: 2

Views: 5345

Answers (2)

John Zwinck
John Zwinck

Reputation: 249133

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.

Upvotes: 3

this.josh
this.josh

Reputation: 683

Try

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

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

Upvotes: 0

Related Questions