Escape characters contained in bash variable in regex pattern

In my bash script, I am trying to execute the following Linux command:

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

$ data_line is entered by the user and can encode special characters that can slow down the regular expression. How can I avoid all possible special characters in $ data_line before I execute the sed command?

+4
source share
2 answers

You may be able to use this method to protect the selector. Lines marked with the " ***** " below are significant lines. Others are mainly for testing and demonstration. The key must use a character that is not displayed in user input in order 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 GOLD in them thar hills!" echo "$excitement" | sed "/$data_line/ d" # output: "LEAD, I tell you, thar LEAD in them thar hills!" # test WITH protection echo "$excitement" | sed "\\${char}${data_line}${char} d" # ***** # output: "GOLD, I tell you, thar 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 GOLD in them thar hills!" 
+4
source
 grep -v -F "$data_line" "$data_dir" > ... 
+4
source

Source: https://habr.com/ru/post/886218/


All Articles