简体   繁体   中英

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?

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

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 (ie 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)

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

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