首页 > 解决方案 > 将多个目录中的文件重命名(递归)为目录名(linux)

问题描述

我试图弄清楚如何重命名我的目录结构(电影)中的文件并统一那里的名称......

有什么办法可以实现以下场景?

例子:

\tmp\test\my folder\v.txt
\tmp\test\my folder\w.pdf

\tmp\test\test folder\my subfolder\x.jpg
\tmp\test\test folder\my subfolder\y.log

\tmp\test\new folder\my path\tester\z.png

预期结果:

\tmp\test\my folder\my folder.txt
\tmp\test\my folder\my folder.pdf

\tmp\test\test folder\my subfolder\my subfolder.jpg
\tmp\test\test folder\my subfolder\my subfolder.log

\tmp\test\new folder\my path\tester\tester.png

我正在尝试一些东西,但这对于像我这样的新手来说太过分了:)

谢谢

标签: linuxbashcommand-line-interface

解决方案


一个基本的解决方案是:

#!/bin/bash

#list the files
files=$(find . -type f)

#go through each file
while read -r file
do
  #get folder path
  folderPath=$(cd "$(dirname "$file")" && pwd)

  #get file subfolder name
  subfolder=${folderPath##*/}

  #get file extension
  extension=${file##*.}

  #rename the file from old name to new name
  mv "${file}" "${folderPath}/${subfolder}.${extension}"
done <<< "$files"

推荐阅读