Reputation: 119
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
Upvotes: 6
Views: 4621
Reputation: 85590
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"
Upvotes: 13
Reputation: 11
This could also be a way
for i in `find . -type f `;do filename=`ls $i | cut -f 2 -d "."`; mv $i ./$filename.ext; done
Upvotes: 1
Reputation: 791
You might want to try the below. It uses find and awk with system() to remove the extension:
find . -name "*" -type f|awk 'BEGIN{FS="/"}{print $2}'|awk 'BEGIN{FS="."}{system("mv "$0" ./"$1"")}'
example:
[root@puppet:0 check]# ls -lrt
total 0
-rw-r--r--. 1 root root 0 Oct 5 13:49 abc.ext
-rw-r--r--. 1 root root 0 Oct 5 13:49 something.gz
[root@puppet:0 check]# find . -name "*" -type f|awk 'BEGIN{FS="/"}{print $2}'|awk 'BEGIN{FS="."}{system("mv "$0" ./"$1"")}'
[root@puppet:0 check]# ls -lrt
total 0
-rw-r--r--. 1 root root 0 Oct 5 13:49 abc
-rw-r--r--. 1 root root 0 Oct 5 13:49 something
also if you have a specific extension that you want to add to all the files, you may modify the command as below:
find . -name "*" -type f|awk 'BEGIN{FS="/"}{print $2}'|awk 'BEGIN{FS=".";ext=".png"}{system("mv "$0" ./"$1ext"")}'
Upvotes: 0