133

I am trying to redirect the output of a bash command into a new file.

If I try the pipe as below :

ls -la | vim

Bash shows me the errors :

Vim: Error reading input, exiting...
Vim: preserving files...
Vim: Finished.

I know that I can open Vim and then use :

:r !ls -la

But is there a way to do this in bash itself, so that Vim is opened and the output is pasted there automatically?

muru
  • 207,228
faizal
  • 3,037

7 Answers7

213

You can use process substitution (this also works with applications that can't read from STDIN):

vim <(ls -la)

Or use vim's function to read from STDIN:

ls -la | vim -
muru
  • 207,228
chaos
  • 28,186
62

You're really close on your own. You were just missing one character.

ls -la | vim -
Cris Holdorph
  • 979
  • 1
  • 7
  • 9
25

Here's another approach, hopefully to teach someone something new.

If you know that the command :r !ls -la works inside vim, you can do the following to open vim and make it run the command as soon as it opens, straight from bash:

vim -c ':r! ls -la'

This is the equivalent of opening vim then executing the command :r! ls -la. This should work with any vim command, where the command comes after the -c option.

Alaa Ali
  • 32,213
15

You can tell vim to open stdin:

ls -la | vim -
iffy
  • 1,127
2

I would like to add an option

ls -al | view -

view is a read-only version of vim(equivalent to vim -R)

2

setlocal buftype=nofile

This is a good option if you are going to create an alias to replace less:

seq 100 | vim +':setlocal buftype=nofile' -

Now you don't need to type the ! to quit.

Another option is:

seq 100 | vim +'nnoremap q :quit!' -

so you can exit with just q<enter>.

1

If your goal is simply to get the output into a text file then you don't need to invoke vim. Bash can do it alone with

ls -la > outputfile.txt