以正则表达式模式转义bash变量包含的字符
发布时间:2020-12-14 05:56:31 所属栏目:百科 来源:网络整理
导读:在我的bash脚本中,我正在尝试执行以下 Linux命令: sed -i "/$data_line/ d" $data_dir $data_line由用户输入,它可能包含可能制动正则表达式的特殊字符. 在执行sed命令之前,如何在$data_line中转义所有可能的特殊字符? 解决方法 您可以使用此技术来保护选择
在我的bash脚本中,我正在尝试执行以下
Linux命令:
sed -i "/$data_line/ d" $data_dir $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,thar's LEAD in them thar hills!" # test WITH protection echo "$excitement" | sed "${char}${data_line}${char} d" # ***** # output: "GOLD,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 "$excitementn$mystery" | sed "${char}${data_line}${char} d" # output: "GOLD,thar's GOLD in them thar hills!" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |