Yesterday I was faced with a task where I wanted to repeatedly edit the first N lines of a file, then when they were in the form I wanted insert them into another file to be consumed by another script. A braindead way to do this would be something like:
:0, d
:w
:e t
:$
:p
:0, d
:w
:e#
This is:
- delete the lines from the beginning of the file to the current line.
- save my file with these lines deleted
- switch to my destination file to be overwritten and go to the end
- paste in the new content
- delete the old content
- save this new destination file
- return to my original file
If you only need to do this once or twice, it’s not that many keystrokes, and can be done really quickly. However, it occurred to me that this can all be done with a one liner instead, cool enough to share:
:0,!cat > t
Here’s what happens:
- Filter the lines from the beginning of the file to the current line through a script
- This script has no stdout, so those lines are deleted from the current file.
- That script uses cat to read from stdin and write the lines to a file, overwriting the destination file as desired
This is a pretty slick technique, but involves a few subtleties. As it happens, my consumer of the moved lines was also a vim editing session, so I’m sure this was probably also possible with a split screen vim. However, I like my screen real estate, and didn’t opt to go that route (and am not actually sure of the keystrokes required to do the same task in a split screen vim session).