How to insert a line in a file between two blocks of known lines (if not already inserted previously), using bash?

前端 未结 3 518
执念已碎
执念已碎 2020-12-11 06:50

I wrote a bash script which can modify php.ini according to my needs.
Now I have to introduce a new change, and I cannot find a clear solution to it.

I need to

相关标签:
3条回答
  • 2020-12-11 07:06

    This might work for you:

     sed '/^; Dynamic Extensions ;$/,/^; Module Settings ;$/{H;//{x;/extension="memcache.so"/{p;d};/;;;\n/{s//&extension="memcache.so"\n/p}};d}' file
    

    This will insert extension="memcache.so" between ; Dynamic Extensions ; and ; Module Settings ; unless extension="memcache.so" is already present.

    0 讨论(0)
  • 2020-12-11 07:15

    You can use the following sed script:

    /^;\+$/{
    N
    /^;\+\n; Module Settings ;$/i extension="memcache.so"
    }
    

    Basically it matches these lines:

    ;;;;;;;;;;;;;;;;;;;
    ; Module Settings ;
    

    and inserts before them the desired string (extension="memcache.so")

    0 讨论(0)
  • 2020-12-11 07:30

    Get the line number using grep -n:

    line=$(cat php.ini | grep -n 'Module Settings' | grep -o '^[0-9]*')
    

    Calculate the line to insert the text to:

    line=$((line - 3))
    

    Insert it using sed or awk. Examples to insert "newline" on line 45:

    sed '45i\newline' file
    awk 'NR==45{print "newline"}1'
    
    0 讨论(0)
提交回复
热议问题