Bash: how to check and insert a string within a block in a file Bash: how to check and insert a string within a block in a file bash bash

Bash: how to check and insert a string within a block in a file


awk '/mime_module/{    flag=1}flag && /x-httpd-php/{    has=1}flag && /<\/IfModule>/{    flag = 0    if(!has)        print "AddHandler application/x-httpd-php .php"}1' input.conf


This might work for you:

sed -i ':a;$!N;/^<IfModule mime_module>.*<\/IfModule>/{s/# *\(AddHandler application\/x-httpd-php \.php\)/\1/;/AddHandler application\/x-httpd-php \.php/!s/.*\n/&\n    AddHandler application\/x-httpd-php .php\n/;p;d};/^<IfModule mime_module>/ba;P;D' input.conf


The following will replace anything inside the block "IfModule - /IfModule" with your text "AddHandler application/x-httpd-php .php". So regardless if the comment (#) is found or if nothing is found the block will have the correct information.

Also it is IMPORTANT to note that this is an inline edit. The file you are wanting changed will be changed immediately upon running this script with NO BACKUP MADE. PRIOR TO TESTING ANYTHING PLEASE BACKUP YOUR FILE.

sed -i '/<\/IfModule>/,/<IfModule>/!s/    \.\.\..*/    \.\.\.\n    AddHandler application\/x-httpd-php .php/g' /yourfile

If you are working on OS X, you may want to try the following script instead

#!/bin/bashCR="$(printf '\r')"sed -i '' "/<\/IfModule>/,/<IfModule>/!s/    \.\.\..*/    \.\.\.${CR}    AddHandler application\/x-httpd-php .php/g" /yourfile

Example of Starting file:

<IfModule>    ...</IfModule><NOTHING TO CHANGE>    ...</NOTHING TO CHANGE><IfModule>    ...#   AddHandler application/x-httpd-php .php</IfModule><NO CHANGE>    ...    NO CHANGE</NO CHANGE>

Results:

<IfModule>    ...    AddHandler application/x-httpd-php .php</IfModule><NOTHING TO CHANGE>    ...</NOTHING TO CHANGE><IfModule>    ...    AddHandler application/x-httpd-php .php</IfModule><NO CHANGE>    ...    NO CHANGE</NO CHANGE>