2010-05-29 122 views
4

在我的bash腳本,我試圖執行以下Linux命令:轉義字符,

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

$ data_line由用戶輸入的,它可能conatain特殊字符可能剎車正則表達式。 我在執行sed命令之前如何轉義$ data_line中所有可能的特殊字符?

+0

如何逃脫在bash http://stackoverflow.com/questions/11856054/bash-easy-way-to-pass-a-raw-string-to-grep/16951928#16951928 – 2013-06-06 00:28:44

回答

4

您可能能夠使用這種技術來保護選擇。下面標有「*****」的行是重要的行。其他人主要是爲了測試和演示。關鍵是要使用不出現在用戶輸入中的字符來分隔選擇器地址。

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!" 
+0

由於正則表達式丹尼斯的詳細答案。我會將其標記爲我接受的答案,因爲它給出了我在問題中提問的答案。但我會使用Ignacio技術,因爲它能以更清潔的方式滿足IMO的要求。 – skujins 2010-05-29 09:41:29

+0

第三行可能是'char = $ {candidates // [$ data_line]}'而不是'echo'和'tr'。 – 2010-05-29 12:27:48

4
grep -v -F "$data_line" "$data_dir" > ...