Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

awk

Having a block in http.conf file like:

<IfModule mime_module>
    ...
</IfModule>

Assuming using bash, how can I check if the following line

AddHandler application/x-httpd-php .php

has been already added within the previous block,
and, if not, how can I add it at its bottom resulting in

<IfModule mime_module>
    ...
    AddHandler application/x-httpd-php .php
</IfModule>

This block is just in the middle of the file:
the file content doesn't start or end with this block.


EDITED:
To make this harder, I realized I need a further check too: sorry to have missed it in my question. If the above line is already present within the mentioned block as a commented line as

# AddHandler application/x-httpd-php .php

(the char # might be the first char of the line or it might have some spaced before, as it might have or not some spaces after before the char A of AddHandler), I simply need to uncomment it, otherwise I have proceed to add it as described.

like image 535
Luca Borrione Avatar asked Jan 16 '23 23:01

Luca Borrione


1 Answers

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
like image 140
kev Avatar answered Feb 05 '23 16:02

kev