views:

37

answers:

2

Hi,

I'm trying to use the linux sed command to append a path element to the RewriteBase in a .htaccess file.

I have tried it with this arguments:

#current RewriteBase is "RewriteBase /mypath"
sed -ie 's/RewriteBase\(.*\)/RewriteBase \1\/add/g' .htaccess

with this result:

addriteBase /mypath

So sed overwrites the the beginning of the replacement string with the last string.

Why is that?

Another question would be how to prevent to have 2 slashes when the RewriteBase is just "/".

RewriteBase /

will become

RewriteBase //add

but should be

RewriteBase /add

Is there any way to prevent this? If not I can run a second sed command replacing all double slashes with a single one. But maybe there is a more elegant way to do this.

I would appreciate any help.

+1  A: 

What you're seeing is sed including the \r in the result, making it look as though the text is being stuck to the beginning. Shove your file through dos2unix before putting it through sed.

As for the second part, you need to capture the optional slash outside the group, then put in /add.

Ignacio Vazquez-Abrams
+1  A: 

If all you want to do is append some text to the line, you don't need backreferences. Try this:

sed -i.bak 's/^M//g;s|RewriteBase.*|&/add|' .htaccess

The special & character represents everything that matched in the pattern space.

Note:

The s/^M//g part is the sed equivalent to dos2unix and the ^M is created by typing <ctrl+v><ctrl+m>.

SiegeX
Thanks a lot for your reply.
dan
Instead of Ctrl-v, Ctrl-m you can just use `\r`: `sed /\r//` (the `g` is not likely to be needed). Here's an alternative to the second part: `/RewriteBase/ s|$|/add|`
Dennis Williamson