[英]Replace/substitute adversarial substring variables in shell script
我有三个未转义的对抗壳变量。
$mystring
$old
$new
请记住,所有三个字符串都是对抗性的。 它们将包含特殊字符。 它们将包含一切可能使替换混乱的事情。 如果替换中存在漏洞,则字符串将利用它。
用$ mystring中的$ new替换$ old的最简单函数是什么? (我无法在堆栈溢出中找到任何适用于所有情况的通用替换解决方案)。
这里没有什么花哨的-确保您在参数扩展中将值视为文字的唯一操作是确保您引用了搜索值,如BashFAQ#21的相关部分所述:
result=${mystring/"$old"/$new}
如果内部没有双引号,则$old
将被解释为fnmatch样式的glob表达式; 与他们,这是字面上的。
要在流上进行操作,请考虑gsub_literal
,这在BashFAQ#21中也有描述:
# usage: gsub_literal STR REP
# replaces all instances of STR with REP. reads from stdin and writes to stdout.
gsub_literal() {
# STR cannot be empty
[[ $1 ]] || return
# string manip needed to escape '\'s, so awk doesn't expand '\n' and such
awk -v str="${1//\\/\\\\}" -v rep="${2//\\/\\\\}" '
# get the length of the search string
BEGIN {
len = length(str);
}
{
# empty the output string
out = "";
# continue looping while the search string is in the line
while (i = index($0, str)) {
# append everything up to the search string, and the replacement string
out = out substr($0, 1, i-1) rep;
# remove everything up to and including the first instance of the
# search string from the line
$0 = substr($0, i + len);
}
# append whatever is left
out = out $0;
print out;
}
'
}
some_command | gsub_literal "$search" "$rep"
...也可用于使用以下技术替换文件(再次取自先前链接的FAQ):
# Using GNU tools to preseve ownership/group/permissions
gsub_literal "$search" "$rep" < "$file" > tmp &&
chown --reference="$file" tmp &&
chmod --reference="$file" tmp &&
mv -- tmp "$file"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.