如何复制文件夹中的每第四个文件

aeb*_*old 15 bash cp files

我在一个文件夹中有很多文件,命名为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
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Sté*_*las 12

使用 zsh,您可以执行以下操作:

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

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
Run Code Online (Sandbox Code Playgroud)

由于这些文件名不包含任何空白或通配符,您还可以执行以下操作:

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


gni*_*urf 7

在 bash 中,一个有趣的可能性,在这里工作得很好:

cp 00802_Bla_Aquarium_*{00..99..4}.jpg selected
Run Code Online (Sandbox Code Playgroud)

这绝对是最短、最有效的答案:没有子shell、没有循环、没有管道、没有awk病房外部进程;只是一个 fork cp(无论如何你都无法避免)和一个 bash 大括号扩展和 glob(你可以完全摆脱,因为你知道你有多少文件)。

  • … 和 2 个假设:文件连续编号,第一个可以被 4 整除。 (4认同)

jfg*_*956 5

只需使用 bash,您就可以执行以下操作:

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

该模式./*.jpg将被 bash 人员所述的按字母顺序排序的文件名列表替换,因此它应该符合您的目的。