ターゲットフォルダが空の場合にのみ、ファイルを1つずつディレクトリに自動的に移動します。

ターゲットフォルダが空の場合にのみ、ファイルを1つずつディレクトリに自動的に移動します。

可能ですか?そしてキャンセルアルファベット順に?

本質的に、これは次のとおりです。タイプ別にファイルをディレクトリとサブディレクトリから別のディレクトリに再帰的に移動する方法は?

各ファイルがターゲットディレクトリに移動されていないだけです。〜しない限り別のプロセスがそのターゲットディレクトリの唯一のファイルをインポートし、別の場所に移動しました。したがって、ターゲットフォルダは空で、次のファイルをそこに移動できるように「準備」されています。

ベストアンサー1

このようなことをしたいですか?

#!/usr/bin/env bash
## This is the target path, the directory
## you want to copy to.
target="some/path with/spaces";

## Find all files and folders in the current directory, sort
## them reverse alphabetically and iterate through them
find . -maxdepth 1 -type f | sort -r | while IFS= read -r file; do
    ## Set the counter back to 0 for each file
    counter=0;
    ## The counter will be 0 until the file is moved
    while [ $counter -eq 0 ]; do
      ## If the directory has no files
      if find "$target" -maxdepth 0 -empty | read; 
      then 
          ## Move the current file to $target and increment
          ## the counter.
          mv -v "$file" "$target" && counter=1; 
      else
          ## Uncomment the line below for debugging 
          # echo "Directory not empty: $(find "$target" -mindepth 1)"

          ## Wait for one second. This avoids spamming 
          ## the system with multiple requests.
          sleep 1; 
      fi;
    done;
done

すべてのファイルがコピーされるまでスクリプトが実行されます。ターゲットが空の場合はファイルをコピーするだけなので、他の$targetプロセスはファイルが入ったときに削除しない限り永久に停止します。

$targetファイル名またはファイルに改行()が含まれていると問題が発生します\nが、スペースやその他の奇妙な文字は問題ありません。

おすすめ記事