如何删除vim中括号内的重复行?

时间:2021-01-06 20:09:47

I have json file that has duplicate values that I wish to remove using vim. Here is an example:

我有json文件,它有重复的值,我希望使用vim删除。这是一个例子:

{
  { "greetings" : [
      "hello",
      "hello",
      "hola",
      "hola"
    ]
  }, ...
}

to

{
  { "greetings" : [
      "hello",
      "hola"
    ]
  }, ...
}

So far, I was able to successfully remove all duplicate lines expect those at the end. There is an extra ',' that breaks my matching and I end up with

到目前为止,我能够成功删除所有重复的行,期望最后的那些。有一个额外的','打破我的匹配,我最终

{
  { "greetings" : [
      "hello",
      "hola",
      "hola"
    ]
  }, ...
}

1 个解决方案

#1


0  

Since duplicated lines are adjacent to each other, you can use \1 to match a string again, and use ,\? to make the comma optional:

由于重复的行彼此相邻,您可以使用\ 1再次匹配字符串,并使用\,?使逗号可选:

:%s/^\(.\+\),\?\n\1\n/\1\r/gc

If you need to limit the search and replace to certain blocks, you can use g/../ to match the block first:

如果您需要限制搜索并替换为某些块,可以先使用g /../匹配块:

:g/[\[^[\]*]/%s/^\(.\+\),\?\n\1\n/\1\r/g 

#1


0  

Since duplicated lines are adjacent to each other, you can use \1 to match a string again, and use ,\? to make the comma optional:

由于重复的行彼此相邻,您可以使用\ 1再次匹配字符串,并使用\,?使逗号可选:

:%s/^\(.\+\),\?\n\1\n/\1\r/gc

If you need to limit the search and replace to certain blocks, you can use g/../ to match the block first:

如果您需要限制搜索并替换为某些块,可以先使用g /../匹配块:

:g/[\[^[\]*]/%s/^\(.\+\),\?\n\1\n/\1\r/g