用sed或awk更改脚本文件的一部分

时间:2016-01-15 22:49:30

标签: bash shell awk sed

我正在尝试编写sed命令来自动更改我的脚本。 此脚本用于根据提供的应用程序版本将SQL修补程序应用于数据库。为了更好地理解,我简化了这个脚本,源代码就像

# something before
if [ "$BRANCH" = "TRUNK" ]
then
    apply_patch.sh 1.0
    apply_patch.sh 2.0
    apply_patch.sh trunk
elif [ "$BRANCH" = "2.0" ]
then
    apply_patch.sh 1.0
    apply_patch.sh 2.0
elif [ "$BRANCH" = "1.0" ]
then
    apply_patch.sh 1.0
fi
# something after

基于两个输入参数(当前版本和下一版本),我需要将此脚本更改为以下

# something before
if [ "$BRANCH" = "TRUNK" ]
then
    apply_patch.sh 1.0
    apply_patch.sh 2.0
    apply_patch.sh 2.1
    apply_patch.sh trunk
elif [ "$BRANCH" = "2.1" ]
then
    apply_patch.sh 1.0
    apply_patch.sh 2.0
    apply_patch.sh 2.1
elif [ "$BRANCH" = "2.0" ]
then
    apply_patch.sh 1.0
    apply_patch.sh 2.0
elif [ "$BRANCH" = "1.0" ]
then
    apply_patch.sh 1.0
fi
# something after

3 个答案:

答案 0 :(得分:2)

关于如何修改逻辑的

草图 我将不得不检查正确的数组语法
但基本上停止重复和重写
只需在修补更改时向阵列添加新元素

ln -s trunk 99999
declare -a appver=( 1.0 2.0 2.1 99999)

for patch in  ${appver[@]} ; do
  if [ ${BRANCH} <= ${patch} ] then 
      apply_patch.sh  ${patch}
  fi
done

答案 1 :(得分:0)

如果版本和补丁号码可以表示为小数,那么您可能需要辅助函数来比较它们。有很多方法可以做到这一点。以下是扩展@ tomc&#39; sketch&#34;:

的示例
#!/bin/bash

function leq {
  awk -v x="$1" -v y="$2" '
    BEGIN { if (x <= y) {exit(0)} else {exit(123)} }'
}

ln -s trunk 99999
appver=( 1.0 2.0 2.1 99999 )

BRANCH="$1"
for patch in  ${appver[@]}
do
  if leq ${BRANCH} ${patch} ; then 
    apply_patch.sh ${patch}
  fi
done

答案 2 :(得分:0)

您的要求非常模糊且不清楚,但可能是您想要的:

$ cat tst.awk
/if.*TRUNK/ { inTrunk = 1 }
inTrunk     {
    if (/elif/) {
        sub(/trunk/,new,buf)
        print buf prev

        sub(/TRUNK/,new,buf)
        print buf $0

        inTrunk = 0
    }
    else {
        buf = buf $0 ORS
        prev = $0
    }
    next
}
{ print }

$ awk -v new=2.1 -f tst.awk file
# something before
if [ "$BRANCH" = "TRUNK" ]
then
    apply_patch.sh 1.0
    apply_patch.sh 2.0
    apply_patch.sh 2.1
    apply_patch.sh trunk
if [ "$BRANCH" = "2.1" ]
then
    apply_patch.sh 1.0
    apply_patch.sh 2.0
    apply_patch.sh 2.1
elif [ "$BRANCH" = "2.0" ]
then
    apply_patch.sh 1.0
    apply_patch.sh 2.0
elif [ "$BRANCH" = "1.0" ]
then
    apply_patch.sh 1.0
fi
# something after
相关问题