Linuxで中身がランダムなテキストファイルを任意のサイズで作成してみました。


この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので十分ご注意ください。

検証環境

・EC2(RedHat Linux 8.4)

背景

AWS DataSyncを使ってデータ移行を検証するため、中身がランダムなテキストファイルを作成して検証しました。ここで検証用テキストファイルの作成方法紹介します。

/dev/urandom について

/dev/urandomというファイルは、カーネル乱数ジェネレータへのインタフェースとしてシステムへ作成されています。 要は乱数を生成してくれるファイルです。単純にファイルとして存在しているので何かのコマンドで中身を出力するとランダムな値を出力してくれます。

テキストのランダムデータを作成する手順

テキストのランダムデータを作成したい場合はbase64コマンドを利用します。

コマンド形式

base64 /dev/urandom | head -c [サイズ] > [ファイル名]

サイズには以下のような単位が使用できます。

b=512
K=1024
M=1024*1024
KB=1000
MB=1000*1000

コマンド例(1MByteのファイルを作成):

base64 /dev/urandom | head -c 1M > testfile-1M

コマンド例(1GByteのファイルを作成):

base64 /dev/urandom | head -c 1024M > testfile-1G

コマンド例(10GByteのファイルを作成):

base64 /dev/urandom | head -c 10240M > testfile-10G

コマンドサンプル(AWS EC2 RadhatLinux8.4)

[ec2-user@ip-10-30-101-77 ~]$ cat /etc/redhat-release
Red Hat Enterprise Linux release 8.4 (Ootpa)
[ec2-user@ip-10-30-101-77 ~]$ base64 /dev/urandom | head -c 1M > testfile-1M
[ec2-user@ip-10-30-101-77 ~]$ ll
total 1024
-rw-rw-r--. 1 ec2-user ec2-user 1048576 Oct 22 01:53 testfile-1M
[ec2-user@ip-10-30-101-77 ~]$ base64 /dev/urandom | head -c 1024M > testfile-1G
[ec2-user@ip-10-30-101-77 ~]$ ll
total 1049600
-rw-rw-r--. 1 ec2-user ec2-user 1073741824 Oct 22 01:53 testfile-1G
-rw-rw-r--. 1 ec2-user ec2-user    1048576 Oct 22 01:53 testfile-1M
[ec2-user@ip-10-30-101-77 ~]$ base64 /dev/urandom | head -c 10240M > testfile-10G
[ec2-user@ip-10-30-101-77 ~]$ ll
total 11535360
-rw-rw-r--. 1 ec2-user ec2-user 10737418240 Oct 22 01:56 testfile-10G
-rw-rw-r--. 1 ec2-user ec2-user  1073741824 Oct 22 01:53 testfile-1G
-rw-rw-r--. 1 ec2-user ec2-user     1048576 Oct 22 01:53 testfile-1M
[ec2-user@ip-10-30-101-77 ~]$

参考

https://tsuredurediary.com/archives/linux-dummy-file.html

Last modified: 2022-10-22

Author