提取外部子文件夹并根据需要重命名

提取外部子文件夹并根据需要重命名

我有一个目录如下:

dhcp-18-189-47-44:CE-06-new-stuctures_backup wenxuanhuang$ ls
DFT-00001 DFT-00004 DFT-00007 DFT-00010 DFT-00013 DFT-00016 DFT-00019 DFT-00022 DFT-00025 DFT-00028 DFT-00031 DFT-00034
DFT-00002 DFT-00005 DFT-00008 DFT-00011 DFT-00014 DFT-00017 DFT-00020 DFT-00023 DFT-00026 DFT-00029 DFT-00032
DFT-00003 DFT-00006 DFT-00009 DFT-00012 DFT-00015 DFT-00018 DFT-00021 DFT-00024 DFT-00027 DFT-00030 DFT-00033

每个文件夹内都有一个名为 Li?Fe?O?_0 的文件,但是其中一些可能会重叠,例如:

dhcp-18-189-47-44:CE-06-new-stuctures_backup wenxuanhuang$ ls DFT-00001/
Li1Fe5O6_0
dhcp-18-189-47-44:CE-06-new-stuctures_backup wenxuanhuang$ ls DFT-00002/
Li1Fe5O6_0
dhcp-18-189-47-44:CE-06-new-stuctures_backup wenxuanhuang$ ls DFT-00010/
Li2Fe4O6_0

现在,我想将子文件夹提取到另一个目录中,我尝试的第一次尝试是:

find `pwd` -mindepth 1 -maxdepth 1 -type d -exec sh -c "echo {}; cd {}; ls; cp -r * /Users/wenxuanhuang/Desktop/software/CASM_NEW/LiFeO_from_Alex_2015_08_25/LiFeO2-CE/02-refinement/CE-06-new-stuctures_extracted" \;

然而,由于命名冲突,其中一些会相互重叠。我想要的是:如果它们重叠:我想将其重命名为不冲突的名称并将其复制到其中......

理想情况下,假设 Li1Fe5O6_0 已经在新文件夹中,我要将另一个 Li1Fe5O6_0 复制到其中,我想将最后一个 Li1Fe5O6_0 命名为 Li1Fe5O6_1 并将该 Li1Fe5O6_1 复制到里面(将来,我们可能会有 Li1Fe5O6_1 Li1Fe5O6_2 Li1Fe5O6_3 等)但如果这个版本的代码太繁琐了。那么就无所谓了...

答案1

这应该做:

#!/bin/bash

# this is the crucial setting: replace a glob pattern that matches zero files
# with nothing (the default is to *not* replace the pattern at all)
shopt -s nullglob

destination=/some/directory

unique_filename() {
    local root=${1%_*}_
    local files=( "$destination/$root"* )
    echo "$destination/${root}${#files}"
}

cd /wherever/you/need/to/go

for f in */Li?Fe?O?_0; do
    echo mv "$f" "$(unique_filename "$(basename "$f")")"
done

它的工作原理是计算目标目录中匹配的文件数量,例如“Li1Fe5O6_*”。如果没有,则使用“Li1Fe5O6_0”。如果“Li1Fe5O6_0”已存在,则$files数组将有一个元素,因此唯一的文件名将为“Li1Fe5O6_1”

相关内容