9

I'm trying to cat some files together, while at the same time adding some text between files. I'm a Unix newbie and I don't have the hang of the syntax.

Here's my failed attempt:

cat echo "# Final version (reflecting my edits)\n\n" final.md echo "\n\n# The changes I made\n\n" edit.md echo "\n\n#Your original version\n\n" original.md > combined.md

How do I fix this? Should I be using pipes or something?

3 Answers 3

9

A process substitution seems to work:

$ cat <(echo 'FOO') foo.txt <(echo 'BAR') bar.txt
FOO
foo
BAR
bar

You can also use command substitution inside a here-document.

$ cat <<EOF
FOO
$(< foo.txt)
BAR
$(< bar.txt)
EOF
Sign up to request clarification or add additional context in comments.

5 Comments

You can embed command substitutions in the here-doc if you don't single-quote FOO.
@chepner Good to know, but how would I use it here?
I've edited your question rather heavily; I don't think you can combine here-strings with other file arguments to cat (in my testing, the here-strings are ignored).
@chepner Ah, I see now, thanks. Never really used here-strings like that.
@chepner Shouldn't there be 2 <'s then? cat <<EOF...
7

Use a command group to merge the output into one stream:

{
   echo -e "# Final version (reflecting my edits)\n\n"
   cat final.md 
   echo -e "\n\n# The changes I made\n\n"
   cat edit.md 
   echo -e "\n\n#Your original version\n\n"
   cat original.md
} > combined.md

There are tricks you can play with process substitution and command substitution (see Lev Levitsky's answer) to do it all with one command (instead of the separate cat processes used here), but this should be efficient enough with so few files.

1 Comment

great option to avoiding having to repeatedly specify the same output file
5

If I understand you, it should be something like:

echo "# Final version (reflecting my edits)\n\n" >> combined.md
cat final.md >> combined.md
echo "\n\n# The changes I made\n\n" >> combined.md
cat edit.md >> combined.md

And so on.

Comments

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.