I want to keep the files but remove their extensions. The files do not have the same extension to them. My end goal is to remove all their extensions and change them to one single extension of my choice. I have the second part down.
My code so far:
#!/bin/bash echo -n "Enter the directory: " read path #Remove all extensions find $path -type f -exec mv '{}' '{}'.extension ; #add desired extension
Advertisement
Answer
You don’t need an external command find
for this, but do it in bash
alone. The script below removes the extension from all the files in the folder path
.
for file in "$path"/*; do [ -f "$file" ] || continue mv "$file" "${file%.*}" done
The reason for using [ -f "$file" ]
is only for a safety check. The glob expression “$path”/* might end up in no files listed, in that case the mv
command would fail as there are no files. The [ -f "$file" ] || continue
condition safeguards this by exiting the loop when the $file
variable is empty in which the [ -f "$file" ]
returns a failure error code. The ||
when used in a compound statement will run if the previous command fails, so when continue
is hit next, the for loop is terminated.
If you want to add a new extension just do
mv "$file" "${file%.*}.extension"