Using bash, how can I remove the extensions of all files in a specific directory?

℡╲_俬逩灬. 提交于 2019-12-10 18:27:40

问题


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

回答1:


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"



回答2:


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



回答3:


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"")}'


来源:https://stackoverflow.com/questions/46586447/using-bash-how-can-i-remove-the-extensions-of-all-files-in-a-specific-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!