Linux Bash 重命名文件

Linux Bash Rename files

我有这样的文件:

./abc/woinewi.mp3
./def/mqwoifkwe.MP3
./ghi/ioqfnw.wmv
./xxx/powijfqiwj.WMV
./yyy/qjwdweo.Mp3

子目录名称是 unique.I 想通过 bash 命令或 scipts 将它们重命名为:

./abc/abc.mp3
./def/def.MP3
./ghi/ghi.wmv
./xxx/xxx.WMV
./yyy/yyy.Mp3

或者像这样:

./abc.mp3
./def.MP3
./ghi.wmv
./xxx.WMV
./yyy.Mp3

有什么办法可以转换吗?谢谢!!!

你可以使用这个:

for f in $(find -type f)
do
    bn=$(basename $f) # file name
    dn=$(dirname $f) # directory name
    newfile=${dn}/$(basename ${dn}).${bn##*.}
    echo mv ${f} ${newfile} 
done

一行:

$ for f in $(find -type f); do bn=$(basename $f); dn=$(dirname $f); echo mv $f ${dn}/$(basename ${dn}).${bn##*.}; done

如果输出符合您的预期,请删除 echo

细分:

find -type f # find all files
dirname somefile # directory name from entry (/1/2/3 -> /1/2)
basename somefile # filename from entry (/1/2/3 -> 3)
${somefile##*.} # get file extension

示例 (cygwin*):

reut@reut-pc ~/test
$ find -type f
./abc/123.456
./def/a.bc

reut@reut-pc ~/test
$ for f in $(find -type f); do bn=$(basename $f); dn=$(dirname $f); echo mv $f ${dn}/$(basename ${dn}).${bn##*.}; done
mv ./abc/123.456 ./abc/abc.456
mv ./def/a.bc ./def/def.bc