逃脱的正则表达式bash的变量包含的字符 [英] Escape characters contained by bash variable in regex pattern
问题描述
在我的bash脚本,我试图执行以下Linux命令:
In my bash script, i am trying to execute following Linux command:
sed -i "/$data_line/ d" $data_dir
$ data_line由用户输入的,它可能conatain特殊字符可以制动器正则表达式。
我怎么能逃避所有在$ data_line可能的特殊字符我执行sed命令之前?
$data_line is entered by user and it may conatain special characters that could brake regex. How can i escape all of the possible special characters in $data_line before i execute sed command?
推荐答案
您可能能够使用这种技术来保障选择。 *****
打上线下面是显著线。其余大多是用于测试和演示。关键是使用不出现在用户输入的字符来分隔选择地址
You might be able to use this technique to protect the selector. The lines marked with "*****
" below are the significant lines. The others are mostly for testing and demonstration. The key is to use a character that doesn't appear in the user input to delimit the selector address.
data_line='.*/ s/GOLD/LEAD/g;b;/.*' # scary user input
candidates='/:.|@#%^&;,!~abcABC' # ***** # (make it as long as you like)
char=$(echo "$candidates" | tr -d "$data_line") # *****
char=${char:0:1} # ***** choose the first candidate that doesn't appear in the user input
if [ -z "$char" ] # ***** this test checks for exhaustion of the candidate character set
then
echo "Unusable user input. Recommendation: cigarette and blindfold."
exit 1
fi
# test without protection
excitement="GOLD, I tell you, thar's GOLD in them thar hills!"
echo "$excitement" | sed "/$data_line/ d"
# output: "LEAD, I tell you, thar's LEAD in them thar hills!"
# test WITH protection
echo "$excitement" | sed "\\${char}${data_line}${char} d" # *****
# output: "GOLD, I tell you, thar's GOLD in them thar hills!"
# test WITH protection and useful user input
data_line="secret"
mystery="The secret map is tucked in a hidden compartment in my saddle bag."
echo -e "$excitement\n$mystery" | sed "\\${char}${data_line}${char} d"
# output: "GOLD, I tell you, thar's GOLD in them thar hills!"
这篇关于逃脱的正则表达式bash的变量包含的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!