Search code examples
unixvimgrepls

Piping the results of *nix commands into Vim's set of open files


I have a folder resembling this structure:

nietzsche.txt
kant.org
buddha.txt
kierkegaard.org
aristotle.txt
plato.org

I wish to read the text files that have the *.org extension, so I use the command:

ls | grep .org

The above command neatly sends the following to stdin:

> kant.org
> kierkegaard.org
> plato.org

I would like to open the files listed above in vim all at once - with the above given example, this is trivial; it would just mean typing out the list of files prefixed with "vim", for example:

vim kant.org kierkegaard.org plato.org

...but in my actual folder of articles there are several hundred plain text files, with the *.org and the *.txt extension. It isn't a matter of converting the org files to true plain text, it's trying to get vim to use the output of other commands through pipes. In reality, the conditions for generating the "books-to-read" list are far more complicated (ie. using date last read, author, date written etc) so a simple find and replace of org-to-txt wouldn't work, as I currently have a bash script to generate the list and spit it to stdout.

How would I get vim to accept the output of a command like grep as a list of files to open immediately?


Solution

  • In this specific example, ls | grep .org is pointless since you can simply do:

    $ vim *.org
    

    As for the general case, you would use $ man xargs on Unix-like systems:

    $ <command that generates a list of files> | xargs -o vim
    

    or:

    $ <command that generates a list of files> | xargs vim --not-a-term
    

    Note that xargs' -o and Vim's --not-a-term are more or less the opposite of each other. The former ensures that xargs passes a proper tty to Vim, while the latter ensures that Vim doesn't complain if there is no attached tty.