简体   繁体   中英

replace the content between some tags with a specific word usin shell script or unix command

I want to replace a specific word between tags. For example, starting withe the following:

<artifactID>abc</artifctID>
<packaging>war</packaging>
<version>1.20.0-SNAPSHOT</version>

I want to find the artifactID tag, then replace 1.20.0-SNAPSHOT with 1.22.0-SNAPSHOT . Note that it has to find the artifactID and replace the version number, which may come in 2nd or 3rd line after artifactID.

I need to do this using a Unix command or a shell script. Thanks in advance.

Below is the script that I have return which should resolve you're issue. I have used, sed command to replace version number. I have return comment to explain the logic

# You can set below two variables based on input argument using "$1" and "$2"
artifact_name="abc"
your_version="your_version"
_count=0
_line=0
while read -r line
do
_line=$((_line+1))
#Search for specific atrifact id
isArtifact=$(echo "$line" | grep ">${artifact_name}<")
# If artifact id found, increment count by 1
if [ "$isArtifact" != "" ]
then 
    _count=1
fi

if [ "$_count" -eq 1 ]
then

    # As we have found the artifact id, now we will search for the version
    isVersionLine=$(echo "$line" | grep -i '<version>')
    echo "$isVersionLine"
    if [ "$isVersionLine" != "" ]
    then
        # Once version is found, replace it with specific version
        sed -i pom.xml -e "${_line}s/<version>.*<\/version>/<version>${your_version}<\/version>/"
        # Increment count to 2 so that no new version is changed. Instead only break will also do
        _count=$((_count+1))
        break
    fi
fi
done < pom.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM