Peter G
Peter G

Reputation: 73

search and replace within specific htaccess files - linux

I need to add this line to every .htaccess file that is located in a /home/*/site/assets/.htaccess where * can be any amount of directories deep

I need to find this text

RewriteRule ^(.*)$ /site/assets/sym/$1 [L,NS]

and add a line above it, or replace it with this

RewriteCond %{REQUEST_URI} !^/site/assets/sym
RewriteRule ^(.*)$ /site/assets/sym/$1 [L,NS]

I've looked online at this site but I am unclear how to deal with

  1. generating a list of the files I want to edit (so find all files that match this path: /home/*/site/assets/.htaccess)
  2. Adding line breaks in the replace text

Can anyone suggest a resource that will clearly explain it, or fail that, let me know if I am looking at the correct tools for this job?

My OS is Cent OS 5.5, i'm running a LAMP server if that makes much difference, apache 2.

Thanks

Upvotes: 2

Views: 499

Answers (1)

user180100
user180100

Reputation:

#!/bin/bash

Something like that:

for dir in `find /home -type d | grep 'site/assets'`
do
    htaccess="$dir/.htacess";
    sed -ibak -e 's@RewriteRule \^\(.*\)\$ /site/assets/sym/\$1 \[L,NS\]@RewriteCond %{REQUEST_URI} !^/site/assets/sym\n\0@' $htaccess
done

On my box:

sed -e 's@RewriteRule \^\(.*\)\$ /site/assets/sym/\$1 \[L,NS\]@RewriteCond %{REQUEST_URI} !^/site/assets/sym\n\0@' test
Foobarlol

RewriteCond %{REQUEST_URI} !^/site/assets/sym
RewriteRule ^(.*)$ /site/assets/sym/$1 [L,NS]
RewriteRule ^(.*)$ /site/assets/test/$1 [L,NS]

Bleh

with test

Foobarlol

RewriteRule ^(.*)$ /site/assets/sym/$1 [L,NS]
RewriteRule ^(.*)$ /site/assets/test/$1 [L,NS]

Bleh

Upvotes: 2

Related Questions