user6778177
user6778177

Reputation: 11

Creating multiple files from text editor

I'd like to create many files from one buffer. Is there an easy way to do this? So starting with

foo1.txt
1a
1b
1c
1d

foo2.txt
2a
2b
2c
2d

foo3.txt
3a
3b
3c
3d

make 3 files, named foo 1 2 and 3 .txt, with the contents.

Is there something less cluncky than this?

echo 1a > foo1.txt
echo 1b >> foo1.txt
echo 1c >> foo1.txt
echo 1d >> foo1.txt

Edit: sorry, the 1a, 1b etc. is meant to symbolize more complex content that I am doing find/replace to in the text editor. I think HERE docs was what I was looking for. Cheers

Upvotes: 0

Views: 112

Answers (4)

Michael Daffin
Michael Daffin

Reputation: 876

You can write multi line files with cat and heredocs:

cat > foo1.txt <<EOF
1a
1b
1c
1d
EOF

cat > foo2.txt <<EOF
2a
2b
2c
2d
EOF

cat > foo3.txt <<EOF
3a
3b
3c
3d
EOF

This will allow variable expansion, so:

cat > test.txt <<EOF
$HOME
EOF

Will produce a file with the path to your home directory. You can supress this by:

cat > test.txt <<"EOF"
$HOME
EOF

Which will produce a file with the contents $HOME rather then the path to your home directory.

Upvotes: 1

user1934428
user1934428

Reputation: 22356

The title of your question doesn't match the question itself, because there is no text editor involved, but maybe you are looking for HERE documents:

    cat >foo1.txt <<EOT
1a
1b
1c
1d
EOT

Upvotes: 0

Chem-man17
Chem-man17

Reputation: 1770

Based on James's answer above but slightly more concise-

   for i in {1..3} #Better if you have to do a lot of files
    do 
        for j in {a..d} #Ditto as above comment
        do 
            echo "$i""$j" >> foo"$i".txt 
        done 
    done

Upvotes: 0

James Brown
James Brown

Reputation: 37464

Like this?:

$ printf '1a\n1b\n1c\n1d\n' > foo1.txt
$ cat foo1.txt
1a
1b
1c
1d

Or maybe:

for i in 1 2 3; do for j in a b c d ; do echo "$i""$j" >> foo"$i".txt ; done ; done

Upvotes: 1

Related Questions