Mv

根據文件名將文件移動到子子文件夾中,用於多個子文件夾

  • June 16, 2020

我有 100 多個子文件夾 ( P_XXX),每個子文件夾包含三組文件 (run1run2) run3

/Analysis   
 /P_076
     /run1
     /run2
     /run3
     swu_run1_P_076_vol_001.nii
     swu_run1_P_076_vol_002.nii
     swu_run2_P_076_vol_001.nii
     swu_run2_P_076_vol_002.nii
     swu_run3_P_076_vol_001.nii
     swu_run3_P_076_vol_002.nii   
  /P_102
     /run1
     /run2
     /run3
     swu_run1_P_102_vol_001.nii
     swu_run1_P_102_vol_002.nii
     swu_run2_P_102_vol_001.nii
     swu_run2_P_102_vol_002.nii
     swu_run3_P_102_vol_001.nii
     swu_run3_P_102_vol_002.nii

我想將這三組文件移動到現有子文件夾中自己的子文件夾(run1、run2 和 run3):

/Analysis
 /P_076
    /run1 
       swu_run1_P_076_vol_001.nii
       swu_run1_P_076_vol_002.nii
    /run2
       swu_run2_P_076_vol_001.nii
       swu_run2_P_076_vol_002.nii
    /run3
       swu_run3_P_076_vol_001.nii
       swu_run3_P_076_vol_002.nii
 /P_102
    /run1
       swu_run1_P_102_vol_001.nii
       swu_run1_P_102_vol_002.nii
     /run2 
       swu_run2_P_102_vol_001.nii
       swu_run2_P_102_vol_002.nii
     /run3
       swu_run3_P_102_vol_001.nii
       swu_run3_P_102_vol_002.nii

當我在子文件夾(P_XXX)中執行腳本時,下面的程式碼可以解決問題:

for f in swu_run?_*.nii; do
      num=${f:7:1}
      mv "$f" run"$num"/
   
done'

但我正在努力尋找合適的for循環以使其從父目錄(分析)工作,而不是在每個子文件夾中手動執行它。我嘗試了以下方法:

find . -type f -name '*.nii' -exec bash -c '
for f in swu_run?_*.nii; do
    num=${f:7:1}
    mv "$f" run"$num"/

done' bash {} +

這將返回錯誤消息cannot stat 'swu_run?_*.nii': No such file or directory.

如何在 Analysis 文件夾級別執行程式碼,以便將每個 P_XXX 子文件夾重新組織到三個另外的子文件夾(run1、run2 和 run3)中,並一次性使用它們的匹配文件?

您可以使用兩個循環bash

cd /path/to/Analysis
shopt -s nullglob
for i in {1..3}; do
 for f in */swu_run${i}_*.nii; do
    mv "$f" "${f%/*}/run${i}/"
 done
done

啟用的nullglobshell 選項可確保在*/swu_run${i}_*.nii不匹配任何文件(已移動或失去)時不進入內部循環。

參數擴展刪除離開父目錄路徑的${f%/*}最短後綴模式。/*

引用自:https://unix.stackexchange.com/questions/593234