将多个目录中的文件重命名(递归)为目录名(Linux)

时间:2018-07-14 11:14:30

标签: linux bash command-line-interface

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

有什么办法可以实现以下方案?

示例:

\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

我正在尝试某些东西,但这对于像我这样的菜鸟来说实在太多了:)

谢谢

1 个答案:

答案 0 :(得分:-1)

一个基本的解决方案是:

#!/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"