Bash

如何復製文件夾中的每4個文件

  • April 13, 2021

我在一個文件夾中有很多文件,名為00802_Bla_Aquarium_XXXXX.jpg. 現在我需要將每4 個文件複製到一個子文件夾中,在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

我該怎麼做呢?

使用 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

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