I've got 2 files (file 1 contains only 1 line; file 2 contains multiple). I want to replace the 5th line in file 2 with the only line present in file 1. What would be the best way to do so?
closed as primarily opinion-based by Anthon, Stephen Kitt, garethTheRed, cas, dr01 Jun 4 '16 at 17:40
Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.
ed combined make an excellent tool for scripted editing of files.
printf '%s\n' '5r file1' 5d w | ed file2
ed to edit
printf command pipes each of its arguments into
ed one at a time, with a linefeed or newline (
\n) between each command.
ed commands are:
5r file1- insert the contents of
file1after line 5
5d- delete line 5
w- write the changed
file2back to disk. Without this, the changes will be discarded when
edexits (i.e. quit without save).
vim /path/to/file1 -c '5' -c 'delete 1' -c '4' -c 'read /path/to/file2' -c 'w /path/to/file3' -c 'q!'
This will use
vim to open
file1, go to the fifth line, delete it, insert the contents of
file2 where that line used to be, and save the result to a new file,