转义字符,
在我的bash脚本,我试图执行以下Linux命令:转义字符,
sed -i "/$data_line/ d" $data_dir
$ data_line由用户输入的,它可能conatain特殊字符可能刹车正则表达式。 我在执行sed命令之前如何转义$ data_line中所有可能的特殊字符?
您可能能够使用这种技术来保护选择。下面标有“*****
”的行是重要的行。其他人主要是为了测试和演示。关键是要使用不出现在用户输入中的字符来分隔选择器地址。
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!"
由于正则表达式丹尼斯的详细答案。我会将其标记为我接受的答案,因为它给出了我在问题中提问的答案。但我会使用Ignacio技术,因为它能以更清洁的方式满足IMO的要求。 – skujins 2010-05-29 09:41:29
第三行可能是'char = $ {candidates // [$ data_line]}'而不是'echo'和'tr'。 – 2010-05-29 12:27:48
grep -v -F "$data_line" "$data_dir" > ...
如何逃脱在bash http://*.com/questions/11856054/bash-easy-way-to-pass-a-raw-string-to-grep/16951928#16951928 – 2013-06-06 00:28:44