简体   繁体   English

sed和转义bash变量的冒险旅程

[英]sed and the odyssey of escaping a bash variable

Having

DEST_PATH='/var/www/clones'
site='xyz.com'

sed -i -e "s/\$log_path\s=\s'\(.*\)'/\$log_path = '$DEST_PATH\/$site\/logs'/" $DEST_PATH/$site/configuration.php

The problem is the forward slashes in first variable, because this is what is being processed and returns error: 问题是第一个变量中的正斜杠,因为这是正在处理并返回错误:

sed -i -e "s/\$log_path\s=\s'\(.*\)'/\$log_path = '/var/www/clones\/xyz.com\/logs'/"  configuration.php

When this is what actually should be run: 这实际上是应该运行的时间:

sed -i -e "s/\$log_path\s=\s'\(.*\)'/\$log_path = '\/var\/www\/clones\/xyz.com\/logs'/"  configuration.php

So I know, I could replace all the / inside $DEST_PATH , and run the sed again, but I was wondering if you know or can think of any other/better way of doing so. 所以我知道,我可以替换$DEST_PATH内的所有/并再次运行sed ,但是我想知道您是否知道或可以想到任何其他/更好的方法。 Ideally, maybe having sed automatically escape the '$DEST_PATH/$site/logs' if possible. 理想情况下,如果可能的话, sed可能会自动转义'$DEST_PATH/$site/logs'

Are you using a modern enough version of sed (eg, GNU sed )? 您是否正在使用足够现代的sed版本(例如GNU sed )? Then you are not required to use / to separate pattern and substitution. 这样就不需要使用/来分隔模式和替换。 Any character will do. 任何角色都可以。

Eg, you can use 例如,您可以使用

s,pattern,substitution,

instead of 代替

s/pattern/substitution/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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