bash 如何使用bash创建具有随机数据的多个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17034941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:39:17  来源:igfitidea点击:

How to create multiple files with random data with bash

macosbashshellscripting

提问by bachkoi32

How do I create multiple files (More than 20k, I need these files to run a test for syncying) with random data in OS X? I used a previously answered question (How Can I Create Multiple Files of Random Data?) that suggested to use something like

如何在 OS X 中使用随机数据创建多个文件(超过 20k,我需要这些文件来运行同步测试)?我使用了先前回答的问题(如何创建随机数据的多个文件?),建议使用类似

dd if=/dev/random bs=1 count=40000 | split -b 2

But using that gives me an error saying too many files.Any other way I can create a loop that will create files with any random data?

但是使用它会给我一个错误,说文件太多。我可以创建一个循环来创建包含任何随机数据的文件吗?

回答by Carl Norum

You can do it with a shell forloop:

你可以用一个 shellfor循环来做到这一点:

for i in {1..20000}; do dd if=/dev/urandom bs=1 count=1 of=file$i; done

Adjust countand bsas necessary to make files of the size you care about. Note that I changed to /dev/urandomto prevent blocking.

调整countbs根据需要制作您关心的大小的文件。请注意,我更改为/dev/urandom以防止阻塞。

You can add some >/dev/null 2>&1to quiet it down, too.

你也可以添加一些>/dev/null 2>&1来让它安静下来。

回答by lurker

Not sure if you have any file naming requirements, but perhaps this:

不确定您是否有任何文件命名要求,但也许是这样的:

for x in {1..20000}; do
  dd if=/dev/random of=test$x.dat bs=10000 count=4
done

回答by Zero Piraeus

The reason your approach doesn't work is that the default suffix for split(2 alphabetic characters) isn't a big enough namespace for twenty thousand files. If you add a couple of options:

您的方法不起作用的原因是split(2 个字母字符)的默认后缀对于两万个文件来说不够大。如果您添加几个选项:

dd if=/dev/random bs=1 count=40000 | split -b 2 -d -a 5

(where -dmeans "use digits, not alphabetic characters, for the suffix" and -a 5means "use suffixes of length 5"), it ought to work fine - I tested it with /dev/urandom(for speed) on a GNU/Linux machine without problems.

(其中的-d意思是“使用数字,而不是字母字符作为后缀”,-a 5意思是“使用长度为 5 的后缀”),它应该可以正常工作 - 我/dev/urandom在 GNU/Linux 机器上用(速度)测试了它,没有问题。

Note that this is much faster than the for-loop approach of the other answers (2.5 seconds versus 43 seconds for Carl Norum's answer on my machine).

请注意,这比其他答案的 for 循环方法快得多(我的机器上 Carl Norum 的答案为 2.5 秒对 43 秒)。