linux - 使用 shell 脚本或 unix 命令用特定单词替换某些标签之间的内容

标签 linux shell unix sh

我想替换标签之间的特定单词。例如,从以下内容开始:

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

我想找到 artifactID 标签,然后将 1.20.0-SNAPSHOT 替换为 1.22.0-SNAPSHOT。请注意,它必须找到 artifactID 并替换版本号,版本号可能位于 artifactID 之后的第 2 或第 3 行。

我需要使用 Unix 命令或 shell 脚本来执行此操作。提前致谢。

最佳答案

下面是我返回的脚本,应该可以解决您的问题。我用过,sed命令替换版本号。我有返回评论来解释逻辑

# 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

关于linux - 使用 shell 脚本或 unix 命令用特定单词替换某些标签之间的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38586842/

相关文章:

linux - 输出重定向是否按顺序写入 stdout 和 stderr 信息?

c++ - C++ 命名空间在 Windows 和 linux 中的行为是否不同?

linux - 自动 qsub 作业完成状态通知

php - 我无法将带有 angularJS 的登录表单发送到 php 文件

linux - 如何在unix中使用awk命令添加?

linux - 我可以在MacOS的_start处通过代码执行 `ret`指令吗? Linux的?

php - 如何让代码在 shell 脚本或 PHP 中每 30 分钟自动运行一次?

linux - AWK 查找第一次出现的字符串并分配给变量进行比较

c - 系统 ("echo text > t.log") 报告错误

bash - 这些 shell 脚本字符 ( || : ) doing anything useful?