18

I need to pass some selected text in vim to a curl command as a parameter value. For example. I need to be able to run

curl -sSd css="body { border-radius: 5px; }" http://prefixr.com/api/index.php

from vim. Obviously, the "body { border-radius: 5px; }" part will be dynamic. Usually, a visual mode selection in vim.

How do I get the selected text and pass it as a parameter to curl?

user1129682
  • 989
  • 8
  • 27
harithski
  • 666
  • 1
  • 6
  • 18
  • Related questions for providing selected text as `STDIN` to shell commands: [Pipe to shell and receive output on info line](http://stackoverflow.com/questions/2575545/vim-pipe-selected-text-to-shell-cmd-and-receive-output-on-vim-info-command-line) and [Piping to and from the shell, working with entire buffers](http://stackoverflow.com/questions/7867356/piping-buffer-to-external-command-in-vim) – user1129682 Feb 17 '14 at 18:04

4 Answers4

22

You can use the :! command to filter selected text through an external program. The text is fed to stdin and substituted with the results from stdout.

In this case you'll have to use cat and command substitution to feed the lines as a parameter to curl, like so:

:'<,'>!curl -sSd css="`cat`" http://prefixr.com/api/index.php
Michał Trybus
  • 11,526
  • 3
  • 30
  • 42
  • Hacky. But that's exactly what I want. Thanks. – harithski Aug 04 '11 at 07:27
  • 10
    This seems to work on lines with selection, not on selected text. For example, if a line is "abcde" and I select "bcd" and run for example `:'<,'>!python3 -c 'print(input()+"x")'` I get "abcdex" instead of "abcdxe". I read somewhere that using `\`<` and `\`>` in place of `'<` and `'>` should operate on selection, but doesn't work for me. – AkiRoss Jan 24 '15 at 12:46
  • It is things like this that make Vim the greatest. Thanks! – mljrg Sep 13 '19 at 12:04
1

By selecting one or more rows and using :! you can pass these lines to a command, for example:

So sort an entire file using the sort command, try this: ggVG !sort, which should look like this in your editor:

B

C

A

:'<,'>!sort

Community
  • 1
  • 1
Jonatan
  • 2,734
  • 2
  • 22
  • 33
  • 1
    I am aware that ! lets you run a shell command, but I want to copy the selection to a *part* the shell command. Not just pipe it. – harithski Aug 04 '11 at 07:29
0

For piping words without gratuitous newlines, see this example to uppercase selected text:

select-region c Control-r = system("perl -pe '$=uc($)'", @")

Explanation: select region, c is to (change selection), C-r to execute expression. Note: dollar is dollar underscore, but underscore not visible after posting.

mosh
  • 1,402
  • 15
  • 16
0

Can't test this right now so not 100% sure if it will work

esc, followed by

:r ! curl -sSd="`cat`" http://prefixr.com/api/index.php`
Kimvais
  • 38,306
  • 16
  • 108
  • 142