简体   繁体   中英

Using SED to append a string to an existing line of text?

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM