【问题标题】:Rename files based on their parent directory in Bash根据 Bash 中的父目录重命名文件
【发布时间】:2018-04-10 03:39:24
【问题描述】:

一直在尝试为这项任务拼凑一些以前的帖子。 目录树如下所示:

TEST
   |ABC_12345678
       3_XYZ
   |ABC_23456789
       3_XYZ
   etc

父文件夹中名为“TEST”的每个文件夹始终以 ABC_\d{8} 开头 - 8 位数字始终不同。在文件夹 ABC_\d{8} 中总是有一个名为 3_XYZ 的文件夹,它总是有一个名为“MD2_Phd.txt”的文件。目标是使用在 ABC 文件夹名称中找到的特定 8 位 ID 重命名每个“MD2_PhD.txt”文件,即“\d{8}_PhD.txt”

在对来自不同帖子的各种代码进行多次迭代之后,这是我能想到的最好的,

cd /home/etc/Desktop/etc/TEST
find -type d -name 'ABC_(\d{8})' |
find $d -name "*_PhD.txt" -execdir rename 's/MD2$/$d/' "{}" \;
done

【问题讨论】:

  • 所有文件的3_XYZ 文件夹是否总是静态名称?
  • 是的,该文件夹在 ABC 中始终命名为 3_XYZ。
  • find 将接受多个目录作为起点,因此find $( find -type d -name 'ABC_(\d{8})' ) -name "*_PhD.txt" -execdir rename 's/MD2$/$d/' "{}" \;(不需要done)。可能有效,除非您的文件或目录名称中有空格,您没有在此处显示。没时间测试。其他答案看起来稍微更直接;-)。祝你好运。

标签: bash find rename


【解决方案1】:

您正在将find 输出传送到另一个find。那是行不通的。

改用循环:

dir_re='^.+_([[:digit:]]{8})/'
for file in *_????????/3_XYZ/MD2_PhD.txt; do
  [[ -f $file ]] || continue
  if [[ $file =~ $dir_re ]]; then
    dir_num="${BASH_REMATCH[1]}"
    new_name="${file%MD2_PhD.txt/$dir_num.txt}" # replace the MD2_PhD at the end
    echo mv "$file" "$new_name"                 # remove echo from here once tested
  fi
done

【讨论】:

【解决方案2】:

find + bash 解决方案:

find -type f -regextype posix-egrep -regex ".*/TEST/ABC_[0-9]{8}/3_XYZ/MD2_Phd\.txt" \
-exec bash -c 'abc="${0%/*/*}"; fp="${0%/*}/";
 mv "$0" "$fp${abc##*_}_PhD.txt" ' {} \;

查看结果:

$ tree TEST/ABC_*
TEST/ABC_12345678
└── 3_XYZ
    └── 12345678_PhD.txt
TEST/ABC_1234ss5678
└── 3_XYZ
    └── MD2_Phd.txt
TEST/ABC_23456789
└── 3_XYZ
    └── 23456789_PhD.txt

【讨论】:

  • 由于某种原因我一开始没有看到这个......我也会试试这个,谢谢@RomanPerekhrest
  • 非常好的解决方案!谢谢你们 - 这两种方法将有助于对出现的其他问题进行轻微修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 2013-10-25
  • 2012-09-12
  • 2012-04-26
  • 2018-12-07
  • 2021-06-05
  • 2015-08-02
相关资源
最近更新 更多