tags:

views:

166

answers:

4

I'm trying to write a shell script that does a search and replace inside a configuration file upon start-up.

The string we're trying to replace is:

include /etc/nginx/https.include;

and we want to replace it with a commented version:

#include /etc/nginx/https.include;

The file that contains the string that we want to replace is:

/etc/nginx/app-servers.include

I'm not a Linux guru and can't seem to find the command to do this.

+7  A: 
perl -p -i -e 's%^(include /etc/nginx/https.include;)$%#$1%' /etc/nginx/ap-servers.include

If the line might not end in the ;, use instead:

perl -p -i -e 's%^(include /etc/nginx/https.include;.*)$%#$1%' /etc/nginx/ap-servers.include

If you want to preserve the original file, add a backup extension after -i:

perl -p -i.bak -e 's%^(include /etc/nginx/https.include;)$%#$1%' /etc/nginx/ap-servers.include

Now, explaining. The -p flag means replace in-place. All lines of the file will be fed to the expression, and the result will be used as replacement. The -i flag indicates the extension of the backup file. By using it without anything, you prevent generation of backups. The -e tells Perl to get the following parameter as an expression to be executed.

Now, the expression is s%something%other%. I use % instead of the more traditional / to avoid having to escape the slashes of the path. I use parenthesis in the expression and $1 in the substituted expression for safety -- if you change one, the other will follow. Thus, %#$1% is actually the second % of s, followed by the desired #, $1 indicating the pattern inside parenthesis, and the last % of s.

HTH. HAND.

Daniel
+1 for the solution and for using another better character for this case (%) instead of the more traditional /
Stefano Borini
+2  A: 

Check out sed.

Amber
A: 
cd pathname
for y in `ls *`;
do sed "s/ABCD/DCBA/g" $y > temp; mv temp $y;
done

This script shold replace string ABCD to DCBA in all the files in pathname

Kazoom
+1  A: 

sed -i 's/foo/bar/g' config.txt

This replaces all instances of foo (case insensitive) with bar in the file config.txt

Clinton Bosch