Gofrolist
Gofrolist

Reputation: 85

Change part of script file by sed or awk

I'm trying to write sed command to change my script automatically. This script is using to apply SQL patches to database based on provided version of application. For better understandings I simplify this script and source looks like

# 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

Based on two input arguments (current version and next version) I need to change this script to the following

# 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

Upvotes: 0

Views: 125

Answers (3)

tomc
tomc

Reputation: 1207

Sketch of how you might rework your logic
I will have to check up correct array syntax
but basically stop repeating and rewriting
and just add a new element to your array when patching changes

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

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 204218

Your requirements are very vague and unclear but MAYBE this is what you want:

$ 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

Upvotes: 0

peak
peak

Reputation: 116880

If the version and patch numbers can be represented as decimals, then you'll probably want a helper function to compare them. There are many ways this can be done. Here is an example expanding on @tomc's "sketch":

#!/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

Upvotes: 0

Related Questions