外部サブフォルダを抽出し、必要に応じて名前を変更します。

外部サブフォルダを抽出し、必要に応じて名前を変更します。

次のディレクトリがあります。

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_6このバージョンのコードがあまりにも面倒です。それでは関係ありません...

ベストアンサー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配列には1つの要素があるので、唯一のファイル名は「Li1Fe5O6_1」です。

おすすめ記事