user6778177 user6778177 - 3 months ago 18
Bash Question

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

Answer

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.

Comments