簡體   English   中英

在Bash中根據父目錄重命名文件

[英]Rename files based on their parent directory in Bash

一直試圖拼湊幾個以前的帖子來完成這項任務。 目錄樹如下所示:

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

你正在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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM