VI delete everything except a pattern

不打扰是莪最后的温柔 提交于 2021-02-07 22:32:30

问题


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"

回答1:


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 \(...\).



回答2:


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.




回答3:


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

Explanation and source here.




回答4:


It's quit convenient if you break the replace command into two steps as below. (p.s. I learned this skill from good guide book 《Practical Vim》 recently).

Step 1: Search the contents that you want to keep

  • \v"title":\s.*"
    This will match "title": "someServerName". You can try again and again with command q/ to open the search command window and modify the regular expression (This is the most excellent part I think).
  • \v^.*("title":\s.*").*$
    Then add bracket for latter use and add .* to match other parts that you wish to delete.

Step 2: Replace the matched contents

  • :%s//\1/g Note the original string in this substitute command is the matched part in last search (Very good feature in vim). And \1 means using the matched group which is actually the part you wish to keep.

Hope you can find it more convenient than the long obscure substitute command.




回答5:


I think the most elegant way to solve this is using ':g' More comprehensive details in this link below! Power fo G

It may not fully archive what you're looking, but damn close ;)



来源:https://stackoverflow.com/questions/34637021/vi-delete-everything-except-a-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!