Search code examples
linuxvimcut

How to run cut command in vim and change the current file


How do I run cut command inside vim and change the contents of the file being edited. I tried following but did not work.

:r ! cut -d ":" -f 1 % > %

and some other variants of it. I want to edit the currently open file using cut and want to know how to accomplish this using only cut inside vim itself.


Solution

  • The reason it doesn't work is because the redirection operator > makes the shell truncate the file before the command is executed, so cut sees an empty input file.

    You could instead use :w to pipe the contents of the current buffer to cut via stdin, then redirect to the file:

    :w ! cut -d ":" -f 1 > %
    

    This has a side effect of Vim prompting you to reload the file. You can use alternatives that don't exhibit this behaviour, such as a substitution:

    :%s/:.*//
    

    or a filter command:

    :% ! cut -d ":" -f 1