3

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?

Anthon
  • 79,293
Dan
  • 31

2 Answers2

3

printf and ed combined make an excellent tool for scripted editing of files.

printf '%s\n' '5r file1' 5d w | ed file2

This uses ed to edit file2. The printf command pipes each of its arguments into ed one at a time, with a linefeed or newline (\n) between each command.

The ed commands are:

  • 5r file1 - insert the contents of file1 after line 5
  • 5d - delete line 5
  • w - write the changed file2 back to disk. Without this, the changes will be discarded when ed exits (i.e. quit without save).
cas
  • 78,579
  • What is the output here? I got three fields where second is number and last one question mark. Etc printf "%s\n" "${l}i" 'level3(ralt_switch' w | ed koodi.awk where koodi.awk is your last code here http://unix.stackexchange.com/a/290408/16920. – Léo Léopold Hertz 준영 Jun 17 '16 at 14:48
  • 1
    @masi The output is ed's extremely verbose and helpful way of telling you what it's up to. Use -s to suppress this vital information. read and follow the examples in pinfo ed --node='Introduction to line editing'. BTW, you probably don't want to be editing the awk script itself, unless you're just using (a copy of) it as a convenient text file to edit. – cas Jun 17 '16 at 14:54
  • How does this approach differ from sed approach like putting a line to specific line etc sed -i "2i avatar" file.tex? – Léo Léopold Hertz 준영 Jun 19 '16 at 06:34
  • 1
    The main difference is that unlike almost everything else that does "in-place", ed is a real in-place edit. The modified file has exactly the same inode (so it won't break hard links) and permissions, while sed uses a tempfile and renames it over the original, resulting in a new inode and possibly different perms. – cas Jun 19 '16 at 07:31
  • 1
    Another difference is that you don't have to have a single-quoted script with embedded newlines (which can be annoying to edit on the command line if you don't use, e.g., ^X^E to edit the line with $EDITOR). You just put each line of the insert in its own quoted string. Overall, the syntax of a sed multi-line insert is a minor PITA compared to ed's. – cas Jun 19 '16 at 07:32
1
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, file3.

DopeGhoti
  • 76,081