49

New to scripting. How can I write code to create multiple files (a.txt, b.txt, ... , z.txt)?

Thanks.

Kevin
  • 501
  • 1
  • 4
  • 4

8 Answers8

114

One command to create 26 empty files:

touch {a..z}.txt

or 152:

touch {{a..z},{A..Z},{0..99}}.txt

A small loop to create 152 files with some contents:

for f in {a..z} {A..Z} {0..99}
do
    echo hello > "$f.txt"
done

You can do numbered files with leading zeros:

for i in {0..100}
do
    echo hello > "File$(printf "%03d" "$i").txt"
done

or, in Bash 4:

for i in {000..100}
do
    echo hello > "File${i}.txt"
done
Dennis Williamson
  • 324,833
  • 88
  • 366
  • 429
6
for i in {1..200}; do touch any_prefix_here${i}; done

where i is the count. So example files are employee1 employee2 etc... through to emplyee200

arush436
  • 1,490
  • 17
  • 18
4
echo Hello > a.txt
echo World > b.txt

for i in a b c d e f g; do
    echo $i > $i.txt
done

If you want more useful examples, ask a more useful question...

cdhowie
  • 144,362
  • 22
  • 272
  • 285
  • 5
    Not everyone is a bash (or shell) expert. It is so easy to do everything with executables it can be easy to forget about built-in flow control tools. – Cody Allan Taylor Nov 09 '17 at 06:56
4

To create files with names a.txt and b.txt simple pass names to touch

touch a.txt b.txt
vovan
  • 1,345
  • 11
  • 21
1

You can create a file using $ cat > a.txt. If you need to have a file with specific content, type $ echo content > filename.

user472875
  • 3,045
  • 4
  • 33
  • 67
1

to have some content in file use dd

for i in {1..N};
do
dd if=/dev/urandom of=./path/file${i} bs=1M count=1;
done
user3156262
  • 309
  • 2
  • 12
0

Instead of using filenames a..z i prefer using numbers.

create a script like this (createNfiles.sh)

#!/bin/bash

if [ "$1" = "" ]; then
  echo "Usage: $0 <number of files to create>"
  exit 1
fi

now=`date '+%Y-%m-%d_%H%M%S'`
prefix="${now}_myFilePrefix"
echo "creating $1 files"
echo "now=$now"

for i in $(seq 1 $1); do file="${prefix}_${i}.log"; echo "creating $file"; touch $file; done

To execute it (create 100 files for example)

./createNfiles.sh 100

drordk
  • 351
  • 2
  • 8
0

tl;dr:

echo CONTENT | tee PATH…

I had to address the content issue to create minimal valid Nix files, which can't be empty:

$ docker run --interactive --rm --tty --volume="${HOME}/dev/root:/etc/nixos" nixos/nix
[…:/# cd /etc/nixos
[…]:/etc/nixos# echo {} | tee common.nix hardware-configuration.nix host.nix
{}
[…]:/etc/nixos# cat common.nix
{}
[…]:/etc/nixos# cat hardware-configuration.nix
{}
[…]:/etc/nixos# cat host.nix
{}
l0b0
  • 52,149
  • 24
  • 132
  • 195