Search code examples
awksedtext-editortext-formatting

Is it possible to add some text at beginning of a file in CLI without making new file?


I have two files file1 containing -

hello world
hello bangladesh  

and file2 containing -

Dhaka in Bangladesh
Dhaka is capital of Bangladesh  

I want to new file2 as -

hello world
hello bangladesh 
Dhaka in Bangladesh
Dhaka is capital of Bangladesh

This is done by -

cat file1 file2 >> file3
mv file3 file2  

But, I don't want to create new file. I guess using sed it may be possible.


Solution

  • Sure it's possible.

    printf '%s\n' '0r file1' x | ex file2
    

    This is a POSIX-compliant command using ex, the POSIX-specified non-visual predecessor to vi.

    printf is only used here to feed a command to the editor. What printf outputs is:

    0r file1
    x
    

    x is save and exit.

    r is "read in the contents of the named file."

    0 specifies the line number after which the read-in text should be placed.

    N.B. This answer is fully copied from Is it possible to add some text at beginning of a file in CLI without making new file?

    Another solution
    There aren't a lot of ways to modify files in place using standard tools. Even if they appear to do so they may be using temporary files (i.e. GNU sed -i).

    ex on the other hand, will do the trick:

    ex +'0r file2' +wq file1
    

    ex is a line editor and vim evolved from it so these commands may look familiar. 0r filename does the same thing as :0r filename in vim: insert the specified file after the given address (line number). The line number here is 0 which is a kind of virtual line that represents the line before line 1. So the file will be inserted before any existing text.

    Then we have wq which saves and quits.

    That's it.

    N.B. This answer is fully copied from https://unix.stackexchange.com/a/414408/176227