如何将文件多次复制到文件系统中随机选择的路径中?

Abd*_*red 5 command-line shell-script random

我有一个文件系统和一个特殊文件 foo. 我希望脚本选择多次(5,10 或 100)个随机路径到此文件系统中的文件夹,并将文件 foo 复制到每个文件夹中。

在此处输入图片说明

我有一个想法,但还不足以根据它制作一个真正的脚本,并且不知道从性能的角度来看这个想法是否有意义。

   idea in pseudo-script:

    read into variable n how many random paths should be found
    file / -type d > file  # put all existing directory paths into a file
    repeat n-times{
    choose_random_line<file | xargsintosecondargument cp foo 
   /* chose a random line from file and use it as second argument of copy
    command, first is foo. */
    }
Run Code Online (Sandbox Code Playgroud)

Sté*_*las 9

在 GNU 系统上:

find / -type d -print0 | shuf -zn5 | xargs -r0n1 cp foo
Run Code Online (Sandbox Code Playgroud)

(现在将文件复制到 /sys 或 /proc 之类的内容没有意义,甚至不可能,您可能只想添加-xdev到安装在 的文件系统上的选定目录中/)。

您可以通过以下方式使其与 FreeBSD 和 GNU 兼容:

find / -type d -print0 | sort -zR | tr '\0\n' '\n\0' | head -n5 |
  tr '\0\n' '\n\0' | xargs -r0n1 cp foo
Run Code Online (Sandbox Code Playgroud)

  • @AbdulAlHazred 因为换行符与文件路径中的任何字符一样有效。NUL 字符是唯一一个不会出现在文件路径中的字符。那些 `-print0`、`-z`/`-0`/`--null` 选项主要是为了能够可靠地处理文件列表。 (2认同)