bashsedgnu-sed

sed append text after N-th occurrence


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?


Solution

  • 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.