0

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

2
  • 2
    which text editor are you using? Commented Aug 31, 2016 at 10:04
  • 5
    for suffix in {1..3}; do echo "whatever" >> "foo${suffix}.txt"; done? Commented Aug 31, 2016 at 10:07

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

0

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

2 Comments

Sorry, the 1a 1b etc. was meant to symbolize content, I'm using the text editor to find/replace etc. I think HERE documents is what I was looking for though, thanks!
In this case, please select the answer as accepted, to show that you don't need more suggestions on this topic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.