Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VI delete everything except a pattern

I have a huge JSON output and I just need to delete everything except a small string in each line.

The string has the format

"title": "someServerName"

the "someServerName" (the section within quotes) can vary wildly.

The closest I've come is this:

:%s/\("title":\s"*"\)

But this just manages to delete

"title": "

The only thing I want left in each line is

"title": "someServerName"

EDIT to answer the posted question:

The Text I'm going to be working with will have a format similar to

{"_links": {"self": {"href": "/api/v2/servers/32", "title": "someServerName"},tons_of_other_json_crap_goes_here

All I want left at the end is:

"title": "someServerName"
like image 626
Carl_Friedrich_Gauss Avatar asked Dec 24 '22 10:12

Carl_Friedrich_Gauss


2 Answers

It should be .* rather than * to match a group of any characters. This does the job:

%s/^.*\("title":\s".*"\).*$/\1/

Explanation of each part:

  • %s/ Substitute on each matching line.
  • ^.* Ignore any characters starting from beginning of line.
  • \("title":\s".*"\) Capture the title and server name. ".*" will match any characters between quotes.
  • .*$ Ignore the rest of the line.
  • /\1/ The result of the substitution will be the first captured group. The group was captured by parentheses \(...\).
like image 66
Jim K Avatar answered Jan 14 '23 19:01

Jim K


This sounds like a job for grep.

:%!grep -o '"title":\s*"[^"]*"'

For more help with Vim's filtering see :h :range!.

See man grep for more information on the -o/--only-matching flag.

like image 21
Peter Rincker Avatar answered Jan 14 '23 19:01

Peter Rincker