Running a command on a visual selection in Vim

As noted in Replacing Text in Vim with the Output of a Command, it can be handy to pipe a bit of text into another command.

For instance, we may have found a JSON Web Token (JWT), like the below:

{
  "client_assertion": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}

If we have a handy executable called jwt, we'd want to create a visual selection inside the quotes around the JWT, and then:

Running

If you just want to just run the command, leaving the JWT in the buffer untouched, you can do the following:

y:echo system('jwt', @")

For example:

Replacing

If you just want to replace the JWT with the unpacked header and payload (if a JWS), you can do the following:

c<C-R>=system('jwt', @")<CR><ESC>

For example:

You may want to toggle :set paste before and after, so the text doesn't get autoformatted by Vim when being inserted.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

This blog post is 100% human-written, and has nothing derived from LLMs (be it code, editorial support or prose).

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.