S
S
Stigunya2014-08-12 00:13:51
bash
Stigunya, 2014-08-12 00:13:51

Bash: Replacing matches between certain strings?

Please tell me how can I replace the text that is between the line that contains AAA and the line that contains BBB.
Text example:

<Directory /var/www/123.ru>
        Options -Includes +ExecCGI
        FCGIWrapper /var/www/php-bin/test/php .php
        FCGIWrapper /var/www/php-bin/test/php .phtml
</Directory>

Task: Replace between
<Directory /var/www/123.ru>and </Directory>
all matches of FCGIWrapper /var/www/php-bin/test/php with FCGIWrapper /var/www/php-bin/test/php5
I don't even know what to use. I will be very grateful for the regular.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Semyon Voronov, 2014-08-12
@Gineaser

#!/bin/bash

FILE="$1"
PATTERN="$2"
PATH1=$3
PATH2=$4

LINES=$(grep -n -A4 "${PATTERN}" ${FILE} | grep FCGI | cut -d "-" -f1)

for line in ${LINES}
do
    sed -i "${line}s|${PATH1}|${PATH2}|" ${FILE}
done

cat ${FILE}

1. You get the line numbers that need to be replaced. To do this, use grep with the -A4 option which means to print the next 4 lines relative to the match. For these lines, thanks to the -n parameter, numbers will be displayed, cut will leave only them.
2. For each line number found, a replacement is made.
The script is called like this, respectively, like this:
script <file> <beginning of block> <what to replace> <what to replace>
Before running, I advise you to save the original file, for example, add it to the loop before sed
cp ${FILE} ${FILE}.bk

3
3vi1_0n3, 2014-10-09
@3vi1_0n3

Actually, it's even easier:

sed -i file -re "/Directory/,/\/Directory/ {s/(test\/php)/\15/}"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question