EricImprint
EricImprint

Reputation: 177

Sed over BASH escaping

I am looking to go through our site and remove the encoded hard paths and replace them with $_SERVER['DOCUMENT_ROOT'] over a shell connection, but I am not sure how to escape it correctly.

Need to replace

"/home/imprint/public_html/template

With

$_SERVER['DOCUMENT_ROOT']."/template

Here is what I found to do it, but I also need to include .htm files and I am not sure what I need to escape.

find . -name '*.php' -exec sed -i 's/"/home/imprint/public_html/template/$_SERVER['DOCUMENT_ROOT']."/template/g' {} \;

Also, what does the -i option do in sed?

Upvotes: 0

Views: 61

Answers (3)

clt60
clt60

Reputation: 63952

Maybe you can try the next

shopt -s globstar
perl -i.bak -pe 's:/home/imprint/public_html/(template):\$_SERVER['DOCUMENT_ROOT']/$1:' ./**/*.php
  • will create backup file .bak
  • the ./**/*.php will search for all php files recusively if the globstar option is set

Upvotes: 0

Alexandre Halm
Alexandre Halm

Reputation: 989

If you're replacing a fixed string with another one, you can use sed with single quotes rather than doubles, as it will prevent any interpretation of the $ sign or other unpredicted funkiness.

Also since you're replacing pathes, fyi you can use other chars than / as sed's delimiter (i.e. sed "s=abc=def=g"), which is probably clearer.

From the man page :

-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied)

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247002

You can combine find clauses with -o ("or")
If you use different delimiters for the sed s command, you don't need to escape anything.

search='"/home/imprint/public_html/template'
replace='$_SERVER['DOCUMENT_ROOT']."/template'

find . -name '*.php' -o -name '*.htm' \
       -exec sed -i "s#${search}#${replace}#g" {} +

To gain efficiency by reducing the number of times sed is invoked, use -exec ... + instead of -exec ... \;

Upvotes: 2

Related Questions