尋找具有特定屬性的文件,將它們重新命名為其目錄名稱,將它們複製到其他地方

尋找具有特定屬性的文件,將它們重新命名為其目錄名稱,將它們複製到其他地方

它看起來不像,但我花了 3 個多小時試圖解決這個問題...我試圖識別具有特定屬性(名稱和大小)的父目錄的所有子目錄中的文件,然後將文件重命名為他們的子目錄名稱並將它們複製到父目錄。我最接近的嘗試(我認為)是:

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

為此,我得到兩行:「cp:目標'/data/data2/parent/3145_V2.nii'不是目錄」我檢查以確保只有一個檔案滿足這兩個屬性,並且確實存在。另外值得注意的是,「parent/」下有兩個子目錄,其中包含一個相關文件,應透過find 命令拾取這些文件,但它僅列印與兩個子目錄之一「parent/3145_v2」有關的錯誤(並且似乎忽略了另一個子目錄) )。

答案1

我有一個喜歡遵循的規則——如果我花費超過 30 分鐘在 bash 中建立單一命令,我就會切換到 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 工具,但它的優點是文件豐富且幾乎沒有錯誤。只是我的兩分錢。

請隨意使用上面的腳本,我測試了它,它工作得很好。乾杯:)

相關內容