Reputation: 335
#!/bin/bash
if [[ "$#" -lt 3 ]]; then
echo "USAGE: enter the following arguments:
1st argument = starting directory path (e.g. . for working directory)
2nd argument = old file extension (e.g. txt)
3rd argument = new file extension (e.g. html
Note: Do not enter any . or \. for the 2nd and 3rd arguments
"
else
find "$1" -name *."$2"* -exec rename 's/\."${2}"$/."${3}"/' '{}' \;
fi
Example input:
bash rename_file_extensions.sh . txt html
Example output:
Use of uninitialized value $2 in regexp compilation at (eval 6) line 1.
line 1
contains the if statement
above. Argument $2
is txt
. So, I am confused as to what it is referring to.
I can run the following line and it works perfectly, but I want to have it accept bash arguments:
find . -name "*.txt.html*" -exec rename 's/\.txt.html.html.html$/.html/' '{}' \;
In this case, as you can see, there were a lot of incorrect file extensions. This line corrected all of them.
I tried editing the find
line to:
find "${1}" -name '*."$2"*' -exec rename 's/\."${2}"$/."${3}"/' '{}' \;
This allowed me to move forward without an error; however, there was no output, and it did not change any txt
extensions to html
when I ran the following command, bash rename_file_extensions.sh . txt html
.
Please help!
Thank you!
Upvotes: 0
Views: 492
Reputation: 140148
to get arguments interpreted by the shell, drop the single quotes:
try
find "$1" -name "*.$2*" -exec rename "s/\.${2}\$/.${3}/" '{}' \;
or (if you want to keep quotes)
find "$1" -name "*.$2*" -exec rename 's/\.'"${2}"'$/.'"${3}"'/' '{}' \;
(and I would enclose the full argument of -name
in double quotes or bash could expand the argument directly if some files match in the current directory)
Upvotes: 1