2

Sorry for a noob question but, well, I am a noob, so...

Given two files, say file1 with content, say, text1 and file2 with content text2, I want to create a new file file3 with content text1newtextinbetweentext2. I would expect some command like

cat file1 (dontknowwhat "newtextinbetween") file2 > file3

Is there some dontknowwhat that would do what I want? If not, what is the optimal way to do it?

2 Answers2

7

Here are two ways:

  1. Group the commands

     $ { cat file1; echo "newtextinbetween"; cat file2; } > file3
     $ cat file3
     text1
     newtextinbetween
     text2
    
  2. Use a subshell

     $ ( cat file1; echo "newtextinbetween"; cat file2 ) > file3
     $ cat file3
     text1
     newtextinbetween
     text2
    
  3. Use command substitution

     $ printf '%s\nnewtextinbetween\n%s\n' "$(cat file1)" "$(cat file2)" > file3
     $ cat file3
     text1
     newtextinbetween
     text2
    

    If you don't want the newlines between each block, you can do:

     $ printf '%snewtextinbetween%s\n' "$(cat file1)" "$(cat file2)" > file3
     $ cat file3
     text1newtextinbetweentext2
    
terdon
  • 242,166
5

Another way to do this is to use process substitution:

cat file1 <(echo "newtextinbetween") file2 > file3

Edit: If you don't what echo to add a line break use echo -n instead.