shell script : replace contents

2019-07-19 18:22发布

问题:

I have file with following info

FileName:VersionInfo.properties

Installed Version:13.7.0-2
Previous Version:13.6.0-12

FileName: rollback.sh

#!/bin/bash
uninstall_rpm ClientInfrastructure $version

How can I get the value into variable $version from Previous Version of VersionInfo.properties file. $version should have the value 13.6.0-12

回答1:

sed solution:

version=$(sed -n 's/Previous Version:\(.*\)/\1/p' VersionInfo.properties)

To use it in a script you can do:

#!/bin/bash
version=$(sed -n 's/Previous Version:\(.*\)/\1/p' VersionInfo.properties)
uninstall_rpm ClientInfrastructure "$version"

If that is all you have in your script then you can basically do it on the command line.

uninstall_rpm ClientInfrastructure "$(sed -n 's/Previous Version:\(.*\)/\1/p' VersionInfo.properties)"


回答2:

version=$(awk 'END {print $2}' FS=':' VersionInfo.properties)


回答3:

Grep + parameter expansion solution:

version=$(grep '^Previous Version:' VersionInfo.properties)
version=${version#*:}
uninstall_rpm ClientInfrastructure $version


回答4:

If the file's written like that you just need the variable $version exported properly.

version=$(awk -F: '/Previous Version/{print $2}') ./rollback.sh

if you really want to change the contents of rollback.sh, use ed:

ed rollback.sh <<< ",s/\$version/$(awk -F: '/Previous Version/{print $2}')/
w" # w must be on newline


标签: bash shell awk sed