How to insert a line into a file between two blocks of known lines (if they have not been inserted before) using bash?

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

I need to modify php.ini to paste (if it has not been inserted before)

extension="memcache.so" 


between the block

;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;

and block

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

maybe just before the second.
Can anybody help me? thanks in advance

EDITED: Permitted by

if ! grep -Fxq 'extension="memcache.so"' 'php.ini'; then
    line=$(cat 'php.ini' | grep -n '; Module Settings ;' | grep -o '^[0-9]*')
    line=$((line - 2))
    sudo sed -i ${line}'i\extension="memcache.so"' 'php.ini'
fi
+5
source share
3 answers

Get line number with grep -n:

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

Compute a string to insert text into:

line=$((line - 3))

sed awk. " " 45:

sed '45i\newline' file
awk 'NR==45{print "newline"}1'
+6

:

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

extension="memcache.so" ; Dynamic Extensions ; ; Module Settings ;, extension="memcache.so" .

+4

sed script:

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

:

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

(extension="memcache.so")

+2

All Articles