2

I can use vim / ex to grep a file using the following invocation:

ex -c'g/foo/p' -cq -s afile.txt

I'd really like to use a similar command to grep some text from stdin. I thought the following command should work, but it produces no output:

cat afile.txt | ex -c'g/foo/p' -cq -s -

The same thing happens if I use vim -e instead of ex:

cat test.md | vim -e -c'g/foo/p' -cq -s -

Is there any way that I can force ex to read its initial buffer from stdin and print output to stdout, so that it can be used within a Unix pipe-line?

4

Move the special filename - before -e:

cat test.md | vim -e -c'g/foo/p' -cq -s -
                                        ^
                                        ✘

cat test.md | vim - -e -c'g/foo/p' -cq -s
                  ^
                  ✔

Before -e, - is read as literal text. After -e, - is read as an Ex command.


To suppress the Vim: Reading from stdin... warning, pass the --not-a-term argument to the vim(1) command:

cat test.md | vim - -e -c'g/foo/p' -cq -s --not-a-term
                                          ^----------^

To make Vim quit, execute :qa! instead of just :q:

cat test.md | vim - -e -c'g/foo/p' +'qa!' -s --not-a-term
                                     ^-^

You can join -e and -s, and you can replace -c with +:

cat test.md | vim - -es +'g/foo/p' +'qa!' --not-a-term
                      ^ ^

You should now be able to pass Vim's output to another shell utility; e.g. wc(1):

cat test.md | vim - -es +'g/foo/p' +'qa!' --not-a-term | wc -l
                                                       ^-----^

See also:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.