フォルダ内の4つのファイルをすべてコピーする方法

フォルダ内の4つのファイルをすべてコピーする方法

私のフォルダに00802_Bla_Aquarium_XXXXX.jpg4位ファイルをサブフォルダー(たとえばselected/

00802_Bla_Aquarium_00020.jpg <= this one
00802_Bla_Aquarium_00021.jpg
00802_Bla_Aquarium_00022.jpg
00802_Bla_Aquarium_00023.jpg
00802_Bla_Aquarium_00024.jpg <= this one
00802_Bla_Aquarium_00025.jpg
00802_Bla_Aquarium_00026.jpg
00802_Bla_Aquarium_00027.jpg
00802_Bla_Aquarium_00028.jpg <= this one
00802_Bla_Aquarium_00029.jpg

どうすればいいですか?

答え1

zshを使用すると、次のことができます。

n=0; cp 00802_Bla_Aquarium_?????.jpg(^e:'((n++%4))':) /some/place

POSIXly、同じアイデアですが、もう少し詳しく説明します。

# put the file list in the positional parameters ($1, $2...).
# the files are sorted in alphanumeric order by the shell globbing
set -- 00802_Bla_Aquarium_?????.jpg

n=0
# loop through the files, increasing a counter at each iteration.
for i do
  # every 4th iteration, append the current file to the end of the list
  [ "$(($n % 4))" -eq 0 ] && set -- "$@" "$i"

  # and pop the current file from the head of the list
  shift
  n=$(($n + 1))
done

# now "$@" contains the files that have been appended.
cp -- "$@" /some/place

これらのファイル名にはスペースやワイルドカードが含まれていないため、次のこともできます。

cp $(printf '%s\n' 00802_Bla_Aquarium_?????.jpg | awk 'NR%4 == 1') /some/place

答え2

Bashでは、これはここでうまく機能する興味深い可能性です。

cp 00802_Bla_Aquarium_*{00..99..4}.jpg selected

これは確かに最短で効率的な答えです。サブシェルもなく、ループもなく、パイプもなく、awkワード外部プロセスもなく、フォークcp(とにかく避けられない)とbashブラケットの拡張とグローブ(なぜなら、あなたがどうするかを知っているからです。)多くのファイルがあるので完全に削除するできます。)

答え3

bashを使用すると、次のことができます。

n=0
for file in ./*.jpg; do
   test $n -eq 0 && cp "$file" selected/
   n=$((n+1))
   n=$((n%4))
done

パターンは、./*.jpgbashユーザーが説明したように、アルファベット順にソートされたファイル名のリストに置き換えられるため、目的に適している必要があります。

答え4

ファイル名に改行文字がないことがわかっている場合は、次のものを使用できます。

find . -maxdepth 1 -name "*.jpg" | sort | while IFS= read -r file; do
  cp "$file" selected/
  IFS= read -r; IFS= read -r; IFS= read -r
done

関連情報