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
  • 234,489
  • 66
  • 447
  • 667
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.

  • Wow this looks even sleeker! But how about avoiding newline between `newtextinbetween` and the contents of `file2`? – მამუკა ჯიბლაძე Dec 03 '20 at 17:26
  • Fantastic! Had to behave ungraciously and move my acceptance from the previous answer to this one. Essentially because what I asked there is very easy to do here, just do `cat file1 <(echo -n $WHATEVER) file2 > file3` – მამუკა ჯიბლაძე Dec 03 '20 at 17:32
  • 4
    @მამუკაჯიბლაძე nothing ungracious about it at all! You should always accept the answer you personally find most useful. Just note that a safer/more portable way would be `cat file1 <(printf '%s' "newtextinbetween") file2 > file3` since not all `echo` implementations understand `-n` (see [Why is printf better than echo?](https://unix.stackexchange.com/q/65803)). – terdon Dec 03 '20 at 18:37
  • @terdon Thanks! Good to know. In my case `-n` worked, I just checked it, so... – მამუკა ჯიბლაძე Dec 03 '20 at 19:48