且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除 Visual Studio Code 中的重复行?

更新时间:2022-12-07 09:39:39

如果行的顺序不重要

按字母顺序对行进行排序(如果还没有),并执行以下步骤:
(基于此相关问题:(全部替换").

如果行的顺序很重要所以你不能排序

在这种情况下,要么求助于 VS Code 之外的解决方案(请参阅此处),或者 - 如果您的文档是不是很大,而且您不介意发送全部替换"按钮的垃圾邮件 - 按照前面的步骤操作,但在第 4 步和第 5 步中,输入以下内容:
(基于删除特定重复行而不排序)

注意:阻止行数过多的文件(1000+);可能会导致 VS Code 崩溃;在某些情况下可能会引入空行.

  • 搜索:((^[^\S$]*?(?=\S)(?:.*)+$)[\S\s]*?)^\2$(?:\n)?

  • 替换为:$1

然后单击全部替换"按钮重复出现的次数.

当您单击按钮时行数停止减少时,您就会知道这就足够了.导航到文档的最后一行以关注该行.

Say you have the following text:

abc
123
abc
456
789
abc
abc

I want to remove all "abc" lines and just keep one. I don't mind sorting. The result should be like this:

abc
123
456
789

If the order of lines is not important

Sort lines alphabetically, if they aren't already, and perform these steps:
(based on this related question: How do I find and remove duplicate lines from a file using Regular Expressions?)

  1. Control+F

  2. Toggle "Replace mode"

  3. Toggle "Use Regular Expression" (the icon with the .* symbol)

  4. In the search field, type ^(.*)(\n\1)+$

  5. In the "replace with" field, type $1

  6. Click ("Replace All").

If the order of lines is important so you can't sort

In this case, either resort to a solution outside VS Code (see here), or - if your document is not very large and you don't mind spamming the Replace All button - follow the previous steps, but in steps 4 and 5, enter these:
(based on Remove specific duplicate lines without sorting)

Caution: Blocks for files with too many lines (1000+); may cause VS Code to crash; may introduce blank lines in some cases.

  • search: ((^[^\S$]*?(?=\S)(?:.*)+$)[\S\s]*?)^\2$(?:\n)?

  • replace with: $1

and then click the "Replace All" button as many times as there are duplicate occurrences.

You'll know it's enough when the line count stops decreasing when you click the button. Navigate to the last line of the document to keep an eye on that.