0
 BASE_NAME="$(basename "${1}")"
 FILE_NEW="$(echo "${BASE_NAME}" | sed -e "${REPLACE}")"

Here $1 refers to the file name that is passed to the function The REPLACE Variable:

REPLACE='s/\[NOW\]/'${NOW}'/g;s/\[TODAY\]/'${TODAY}'/g;s/\[DATETIME\]/'${DATETIME}'/g;s/\[RANDOM\]/'${RANDOM_NUMBER}'/g;s/\[NAME\]/'${NAME}'/g;s/\[FILENAME\]/'${FILENAME}'/g'

What I want to do is modify the file names with the sed operator by replacing the above patterns. But when I come across a file which contains spaces followed by "-" and them something that gives a problem. For an example take to look at the following file names:

file -2.txt
file -3.txt
file -e.txt

In all those cases the errors thrown are as follows:

sed: invalid option -- '2'
sed: invalid option -- '3'
sed: -e expression #1, char 1: unknown command: `.'

If the file name just contans spaces and no "-" still there are problems:

file name.txt

would give the following error:

sed: can't read ./file: No such file or directory
sed: can't read name.txt: No such file or directory

The FULL CODE TO THE SCRIPT: Full Script

rathindu_w
  • 113
  • 3
  • The sed command you give here is ok, but the one in the replace_file_content function is not, and is probably where the error is coming from. The problem (there and a number of other places in the script) is failing to double-quote variable references. Use shellcheck.net to spot common mistakes like this. – Gordon Davisson Dec 17 '20 at 09:34

1 Answers1

2

Your error comes from the following line in the script:

sed -i $REPLACE $1

This is using both the REPLACE variable and $1 unquoted, which means the shell will split these into words on spaces, tabs and newlines (and then additionally process these words for filename globbing patterns). These words will then be given as separate arguments to sed.

You may get away with using

sed -i -e "$REPLACE" -- "$1"

You additionally have a couple of unquoted variables in your clone_directory function:

  rename_file ${dir_name}
  ROOT=$FILE_NEW
  cd $ROOT

and also in your replace_tags function (note that using {...} around variable names is usually not needed and is not equivalent to quoting the variable).

Also note that shell options are not local to functions, so setting extglob in get_file_folder_name would set it globally.

See also:

Kusalananda
  • 333,661
  • Meta question: If the answer is "quote variables" then shouldn't the question be closed as duplicate of the questions you linked to anyway? Should or shouldn't we write the same answer over and over again? – Kamil Maciorowski Dec 17 '20 at 09:40
  • @KamilMaciorowski Because there were other specific things I wanted to tell the user about too. – Kusalananda Dec 17 '20 at 09:42