Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add literal text to the Unix 'cat' command

Tags:

bash

cat

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?

like image 650
incandescentman Avatar asked Feb 14 '13 20:02

incandescentman


People also ask

How do I add text to a cat file?

Type the cat command followed by the double output redirection symbol ( >> ) and the name of the file you want to add text to. A cursor will appear on the next line below the prompt. Start typing the text you want to add to the file.

How do you add text to a file in Unix?

You can use the cat command to append data or text to a file. The cat command can also append binary data. The main purpose of the cat command is to display data on screen (stdout) or concatenate files under Linux or Unix like operating systems.

What is cat command Unix?

Description. The cat command reads one or more files and prints their contents to standard output. Files are read and output in the order they appear in the command arguments.

How do I write to a file in Linux with a cat?

Writing to a File Using cat To write to a file, we'll make cat command listen to the input stream and then redirect the output of cat command into a file using the Linux redirection operators “>”. We'll see that once again the terminal is waiting for our input. However, this time it won't echo the texts we've entered.


2 Answers

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
like image 178
Lev Levitsky Avatar answered Sep 25 '22 14:09

Lev Levitsky


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.

like image 28
chepner Avatar answered Sep 23 '22 14:09

chepner