简体   繁体   中英

How can I escape variable for use with sed?

I have a variable $salts equal

define('AUTH_KEY', 'sBXb~#HPv(X>|2o2&C K&9@l+0.$M,(7-0sW.lpziIZ_EBbHIu3^S}OM-^n,)L S'); define('SECURE_AUTH_KEY', 'RX=tc=pj)y0he{FOqZp/:W{5{@[tnxUv3W_hZ+g4gL)]p!xH-.qb6]O$VHc5V@}1'); define('LOGGED_IN_KEY', '0cUHd}{d)g0X~%Qwy8wKc)cxxXFp2/wCcS=/-sH3z84jz47cV#9|%)1-uTtey(s1'); define('NONCE_KEY', 'J|_J>;_xvHA_UQ^5WDpnpq%,vy{WgNBc{K(SSqwFlwhZCCm>Db^cnBy%9X_q[<^E'); define('AUTH_SALT', '?S15/b~oVY&|ZZp]W<B%uF$<C6c%lIe_!nrVmmPWO`[37C45w9Oju!+xrL~zLnlM'); define('SECURE_AUTH_SALT', 'iX-i>DWhT-0[E1H,[Qqmx;w}$N{B,QAF$W^m9]!1!|_y58aYnHAcXL)l~L|}W39W'); define('LOGGED_IN_SALT', 'qN!?,ORKqNBv@Mf8hb]#VLVYY>+=w*M]|=x^!)>wEl%[]R+(jD{VKOSQueiB8eo('); define('NONCE_SALT', '>,i@yn,CIb<vKOR(2[]*x)SBZzy[T]cq%|[}LBFALEPULwEVa*%C;?b$CZIS-#;*');

I am trying to execute command

cat -n wp-config.php | sed '45,52d' | sed "45i ${salts}"

and get error

sed: -e expression #1, char 102: extra characters after command

How can I escape $salts variable for sed?

Just use awk so you don't spend the rest of your life figuring out which characters you need to escape in which contexts using sed - it's an unsolvable problem and the solutions' trivial in awk and you don't need the cat and multiple pipes either:

awk -v salts="$salts" '
   NR==45 { $0 = salts }
   (NR < 46) || (NR > 52) { print NR, $0 }
' wp-config.php

sed is an excellent tool for simple substitutions on a single line, for anything else just use awk.

this works

cat -n wp-config.php | sed  '45,52d' | sed "45i $(echo $salts | sed -e 's/[\/&]/\\&/g')"

Characters in $salts that have special meaning to sed need to be escaped first.

You can escape variable by:

echo $VARNAME | sed -e 's/[\/&]/\\&/g'

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