regex - 正则表达式模式中 bash 变量包含的转义字符

标签 regex bash sed escaping

在我的 bash 脚本中,我尝试执行以下 Linux 命令:

sed -i "/$data_line/ d" $data_dir

$data_line 由用户输入,它可能包含会破坏正则表达式的特殊字符。 在执行 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!"

关于regex - 正则表达式模式中 bash 变量包含的转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2933474/

相关文章:

javascript - Nodejs readFileSync 两个字符串之间的正则表达式标记

Python:如何通过定义异常来使用re?

bash - 为什么带有 -w (--word-regexp) 标志的 grep 如此缓慢且占用大量内存?

linux - bash:打印:找不到命令

linux sed 命令 - 在 csv 行的每一端添加字符串

javascript - 正则前瞻千位分隔符的正则表达式不会匹配点后的数字

php - SQL从脏数据集创建新数据库

bash - 在继续 bash 之前等待网络链接建立

sed - sed 中的\1 有什么作用?

linux - 如何将 sed 命令组合到 shell 脚本中