Search code examples
linuxbashpipecathead

How do I concatenate two files and write the result back to one of the original files


I am trying to get the first 4 lines from somefile, concatenate them with the contents of someotherfile and output it to somefile.

head -4 /somefile | cat - /someotherfile > /somefile

When I do this the contents of someotherfile ends up in somefile, but not the first 4 lines. If I output to a totally different file then it works great.

Obviously there is an issue with trying to write to the same file I am reading from. What would be the simplest way to accomplish this task?

I am attempting to do this on RedHat Enterprise 6, bash shell.


Solution

  • You can save head output to temporary variable, like this:

    HEAD="$(head -4 some file)"
    (echo "$HEAD"; cat someotherfile) >some file
    

    Or you can remove all lines starting from 5th and append content of another file to the end:

    sed -i '5,$d' somefile
    cat someotherfile >>somefile