【问题标题】:Rename files based on pattern in path根据路径中的模式重命名文件
【发布时间】:2017-06-08 13:32:42
【问题描述】:

我有数千个名为“DOCUMENT.PDF”的文件,我想根据路径中的数字标识符重命名它们。不幸的是,我似乎无法使用重命名命令。

三个例子:

/000/000/002/605/950/ÐÐ-02605950-00001/DOCUMENT.PDF
/000/000/002/591/945/ÐÐ-02591945-00002/DOCUMENT.PDF
/000/000/002/573/780/ÐÐ-02573780-00002/DOCUMENT.PDF

重命名为,不改变其父目录:

2605950.pdf
2591945.pdf
2573780.pdf

【问题讨论】:

  • 我好像无权访问重命名命令,你的意思是你没有能力执行mv 命令?如果原始文件位于/000/000/002/... 中,该文件来自哪个文件夹?当前目录,还是根目录?您希望生成的文件放在哪里?
  • 是的,我可以执行 mv 或 cp。原始文件来自当前目录(不是根目录)。生成的文件可以转到当前目录。感谢您的帮助!
  • mv 是您在 Unix 中“重命名”文件的方式。您将其mov改成不同的名称。

标签: unix rename mv


【解决方案1】:

使用 for 循环,然后使用 mv 命令

for file in *
do
  num=$(awk -F "/" '{print $(NF-1)}' file.txt | cut -d "-" -f2);
  mv "$file" "$num.pdf"
done

【讨论】:

    【解决方案2】:

    您可以在 Bash 4.0+ 中使用 globstar 来做到这一点:

    cd _your_base_dir_
    shopt -s globstar               
    for file in **/DOCUMENT.PDF; do # loop picks only DOCUMENT.PDF files
      # here, we assume that the serial number is extracted from the 7th component in the directory path - change it according to your need
      # and we don't strip out the leading zero in the serial number
      new_name=$(dirname "$file")/$(cut -f7 -d/ <<< "$file" | cut -f2 -d-).pdf
    
      echo "Renaming $file to $new_name"
    
      # mv "$file" "$new_name" # uncomment after verifying
    done
    

    查看这篇讨论类似问题的相关帖子:How to recursively traverse a directory tree and find only files?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-10
      • 2010-11-08
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 2012-09-29
      相关资源
      最近更新 更多