2

I wanted to know how I can create x number of files with content in a folder?

For example:

I want to create 250 files with basic content in my files test folder located in my home directory.

All I really need assistance on is how to create a lot of files with content for testing purpose using bash shell.

Any help would be appreciated.

Nina G
  • 787

3 Answers3

2

You can code a loop that creates a file with content and run it 250 times:

for i in $(seq 1 250) ; do echo -n "content" > ~/test/file$i ; done

Explanation:

  • seq 1 250: show numbers from 1 to 250. It will be used by for to counts how much run you need.
  • echo -n "content" > ~/test/file$i: save "content" to your files in your "test" folder located in your home directory.

I prefer use echo -n > file$i because is more fast than touch file$1:

>> time ./01.sh
./01.sh  0,03s user 0,06s system 28% cpu 0,316 total
>> time ./02.sh
./02.sh  0,01s user 0,00s system 77% cpu 0,017 total

01.sh content:

#!/bin/bash

for i in {001..250} ; do touch ./01/file$i ; done

02.sh content:

#!/bin/bash

for i in {001..250} ; do echo -n > ./02/file$i ; done
1

For start, you can begin with this simple bash for loop:

for i in {001..250} ; do touch ./file$i ; done

This will create 250 empty files in current directory, named file001 till file250.

Touch (in this case) just creates a file, if it does not exist. Empty file. If you want to create files with something in them, you can change the do part of the for loop. For instance do cp ./master.file ./newfile.$i - which will copy file called master.file into the 250 new files and those will be called newfile.001 up to newfile.250.

Is it too confusing? It took me a while to understand how these things work in bash, but once I managed, I use it nearly every day. So feel free to ask, I'll try to explain it more and/or better.

0

In complement to the previous (very good) answer, I will focus on putting some content in the files -- in this case, 3 random English words and a random number:

$ for a in {001..009}
do
(shuf -n 3 /usr/share/dict/words ; echo $RANDOM)  > FILE_$a
done

Example of generated file:

$ cat FILE_005
atrophy
grays
backdate
9612
JJoao
  • 12,170
  • 1
  • 23
  • 45