cat

Some notes on copying and moving text in vim

April 13, 2015 perl and general scripting hackery , ,

Emad just asked me a vim question (how to use a search expression instead of a line number), and I ended up learning a new vim commmand from him as a side effect.

I’d done stuff like the following before to move text to a new file

:,/Done/-1 !cat > /tmp/newfile.txt

This assumes you’d like to delete everything from the current position to the line just before the /Done/ search expression, and write it into /tmp/newfile.txt.

The mechanism here, is that the selection is filtered through a script, where the output of the script is empty, so the lines are deleted. This particular script has the side effect of creating a file with the selected range of lines. The end effect is that the text is moved.

If you’d like to keep it and copy it to the new file, you can tee instead of cat it:

:,/Done/-1 !tee /tmp/newfile.txt

This is faster than selecting a range, switching buffers copying into the buffer, saving, and switching buffers back.

Emad taught me that this can also be done with the w command, like so:

:,/Done/-1 w /tmp/newfile.txt

It doesn’t surprise me that there’s a faster way to copy text from one file to another than using tee, but since I knew one way, I never went looking for it.

vim hacking: move set of lines into new file without buffer switching

May 30, 2014 perl and general scripting hackery , , , ,

 

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).