1

I have a template of the following script and I need to insert the different PARAM value for each case.

case $1 in
1)
    export PARAM=
    ;;
2)
    export PARAM=
    ;;
3)
    export PARAM=
    ;;
esac

I just found an example how to insert the value for the 1st case PARAM:

sed -i '/export PARAM=/{s//export PARAM=1212212121/;:a;n;ba}' file

but how can I do this for cases 2 and 3?

SLePort
  • 15,211
  • 3
  • 34
  • 44
hustas88
  • 307
  • 3
  • 15

2 Answers2

0

Use awk:

awk -v v="1212212121" -v n=2 '/Param/{c++} c==n-1{$(NF)+=" "v}1' file
awk -v v="1212212333" -v n=3 '/Param/{c++} c==n-1{$(NF)+=" "v}1' file

and so on...

Explanation:

  • /Param/{c++} increments a counter c every time the pattern /Param/ is found.
  • c==n-1 checks if c has the desired value and adds the value add the
  • 1 is always true. awk will print all lines.
  • -v v="1212212121" -v n=2 passes the variables v and n to the script.
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

This might work for you (GNU sed):

n=2 v=11212212121
sed -ri '/export PARAM=/{x;s/^/x/;/x{'$n'}/!{x;b};x;s/(export PARAM=).*/\1'$v'/;:a;n;ba}' file

Keep a counter in the hold space and if the counter matches your expectation, substitute and then print out the remainder of the file.

potong
  • 55,640
  • 6
  • 51
  • 83