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?
2 Answers
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 offile1
after line 55d
- delete line 5w
- write the changedfile2
back to disk. Without this, the changes will be discarded whened
exits (i.e. quit without save).
-
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
wherekoodi.awk
is your last code here unix.stackexchange.com/a/290408/16920. Jun 17, 2016 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 inpinfo 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.– casJun 17, 2016 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
? Jun 19, 2016 at 6:34 -
1The 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, whilesed
uses a tempfile and renames it over the original, resulting in a new inode and possibly different perms.– casJun 19, 2016 at 7:31 -
1Another 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 ased
multi-line insert is a minor PITA compared toed
's.– casJun 19, 2016 at 7:32
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
.
vim
, delete the fifth line, and:read /path/to/file1
. Done and done.