特定の属性を持つファイルを検索し、ディレクトリ名に名前を変更し、別の場所にコピーする

特定の属性を持つファイルを検索し、ディレクトリ名に名前を変更し、別の場所にコピーする

そうは思えないかもしれませんが、私はこれを理解するために 3 時間以上を費やしました... 親ディレクトリのすべてのサブディレクトリにある特定の属性 (名前とサイズ) を持つファイルを識別し、そのファイルをサブディレクトリ名に変更して親ディレクトリにコピーしようとしています。私の最も近い試みは次のとおりでした (私の考えでは)。

find /data/data2/parent/ -size 25166176c -name "o*.nii" -exec cp {} $subdir/o*.nii $subdir.nii \;

これに対して、次の 2 行が表示されます: "cp: ターゲット '/data/data2/parent/3145_V2.nii' はディレクトリではありません"。両方の属性を満たすファイルが 1 つだけあることを確認しましたが、確かにありました。また、注目すべきは、"parent/" の下に 2 つのサブディレクトリがあり、find コマンドで取得される関連ファイルがあるのですが、2 つのうちの 1 つである "parent/3145_v2" に関するエラーのみが出力されたことです (もう 1 つのサブディレクトリは無視されているようです)。

答え1

私が守っているルールは、bash で 1 つのコマンドを作成するのに 30 分以上かかったら、Python 3 に切り替えるというものです。

この問題は Python で簡単に解決できます。

#/usr/local/bin/python3

import os, re

DIR_TO_SEARCH = os.getcwd()   #change this to what you want

for (dirpath, dirnames, filenames) in os.walk(DIR_TO_SEARCH):
    if dirpath == DIR_TO_SEARCH:
        # you said you just want subdirectories, so skip this
        continue
    else:
        for name in filenames:
            full_path = dirpath + '/' + name
            #check for the attributes you're looking for. Change this to your needs.
            if re.search(r'o*\.nii', name) or os.path.getsize(full_path) > 0:
                #rename the file to its directory's name, and move it to the parent dir
                print('Moving {} to {}'.format(full_path, dirpath + '.nii'))
                os.rename(full_path, dirpath + '.nii')  

一般的に、Python は bash ツールほどプラグアンドプレイではないかもしれませんが、非常によく文書化されており、バグがほとんどないという利点があります。これは私の意見です。

上記のスクリプトはご自由にお使いください。テスト済みで問題なく動作します。よろしくお願いします :)

関連情報