I want to use the rename command to remove characters on a file basename, based on characters entered (input) by the user in an interactive script.Basically, I would like to do this:read characters_to_remove_inputted_by_the_userrename 's/$characters_to_remove_inputted_by_the_user//g' fileBut I'm having trouble with properly inserting the variable and keep the command structure during the script execution.
Using a variable with rename command
shell script;regular expression;rename;command;variable
Assuming -- as your own command line suggests -- perl's rename implementation (an example script shipped with perl since version 3 in 1989, and often included as a command in many OSes, sometimes as a rewrite with extensions separate from the perl package like this one), sometimes called prename on some Linux distributions where rename is otherwise the one from util-linux, you can use the environment:STRING=$characters_to_remove_inputted_by_the_user rename 's/\Q$ENV{STRING}\E//g' ./*Above, the content of the $characters_to_remove_inputted_by_the_user shell variable is passed as the value of the STRING environment variable which perl retrieves with $ENV{STRING}.Alternatively, you could use the export shell special builtin so that that shell variable be passed in the environment of every command it executes including that rename:export characters_to_remove_inputted_by_the_userrename 's/\Q$ENV{characters_to_remove_inputted_by_the_user}\E//g' ./*The \Q/\E are to make sure $STRING is treated as a fixed string and not a regexp. If you want it to be treated as a regexp, that's just:REGEXP=$characters_to_remove_inputted_by_the_user rename 's/$ENV{REGEXP}//g' ./*Avoid things like:rename s/$characters_to_remove_inputted_by_the_user//g ./*Above the content of the shell variable is expanded by the shell before calling rename, so that could amount to a command injection vulnerability, as the value of the variable would be interpreted as perl code (think for instance of a value like //;system(reboot);s/).