0

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.

2 Answers 2

2

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>.

Sign up to request clarification or add additional context in comments.

1 Comment

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|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.