Search This Blog


Sunday, April 11, 2010

How to insert a file at a specific line and column

My objective is to insert the complete contents of a text file at a specific row and column of another text file.

If we are merely concerned with inserting after a specific line, it can be readily achieved with a number of Linux tools. For example, to insert file1.txt after the second line of file2.txt, any of the following commands will do:

  • $ sed -i '2r file1.txt' file2.txt

  • $ awk '{print} NR==2 {while (getline < "file1.txt") print}' file2.txt

    Unlike the previous sed command which modifies file2 in-line, the above awk command writes the desired output to standard output only.

  • $ emacs -batch +3 file2.txt --insert file1.txt -f save-buffer -kill

    This uses the batch capability of the emacs text editor. The command opens file2 at line 3, inserts file1, saves and then exits.

  • $ vi +2 file2.txt << DELIM
    > :r file1.txt
    > :wq
    > DELIM
    Vim: Warning: Input is not from a terminal

    Note that after you enter the first line ("vi +2 ..."), you will be prompted for more input. At that time, you enter the next three lines (:r, :wq, DELIM)

While Linux has many utilities to manipulate text (sed, perl, awk, cut, python), the easiest way I can think of to accomplish my objective to insert at a target line and column is using emacs.

$ emacs -batch -Q +2:3 file2.txt --insert file1.txt -f save-buffer -kill 2>/dev/null

The key is +2:3 which directs the editor to open the file at line 2 column 3.

Two other components in the above emacs command warrant some explanation. First, -Q means quick startup. Quick, because emacs won't load any init file, or any splash file. Second, the last part of the command pipes any standard error output from the emacs editor to the null device.

I don't doubt that sed, awk or perl can do the job. If you have a simple solution, please share with us via the comment feature of this web page. Many thanks.

StumbleUpon Toolbar


Facebook custom friend selector said...

aha .. nice trick to work with linux comamnd :)

Francesco said...

Defining "perl" as a linux tool is at least a little reductive.
Good tips though :)

Akhil said...

Nice Article.
Some examples on Find Command and Awk Command