Last updated: Apr 6, 2024
Reading time·3 min
To remove the duplicate lines in Visual Studio Code:
Ctrl
+ Shift
+ P
on Windows and LinuxCommand
+ Shift
+ P
on macOSF1
to open the Command Palette.Here is a short clip that demonstrates the process.
Make sure to select the text prior to running the Delete Duplicate Lines command, otherwise it does nothing.
If you need to set a keyboard shortcut for the Delete Duplicate lines command:
Ctrl
+ Shift
+ P
on Windows and Linux.Command
+ Shift
+ P
on macOS.F1
to open the Command Palette.You can also click on the plus icon to add a keyboard shortcut.
Enter
to confirm.For example, I've bound the command to Ctrl
+ F4
.
Here is a short clip in which I use the custom keyboard shortcut.
You can also use a regular expression to remove the duplicate lines.
The following example assumes that the order of the lines in the file is not important.
First, select the lines.
Then, press:
Ctrl
+ Shift
+ P
on Windows and LinuxCommand
+ Shift
+ P
on macOSType sort lines and select Sort Lines Ascending.
Here is a short clip that demonstrates the process.
Press Ctrl
+ F
on Windows and Linux or Cmd
+ F
on macOS to show the
search field.
Type the following regular expression in the Find field -
^(.*)(\n\1)+$
.
^(.*)(\n\1)+$
Click on the arrow to expand the Replace field and enable regular
expression search by clicking on the . *
button.
Type $1
in the Replace field.
$1
Here is a short clip that demonstrates the process.
If you need to remove the duplicate lines and the order of lines is important:
Press Ctrl
+ F
on Windows and Linux or Cmd
+ F
on macOS to show the
search field.
Click on the arrow to expand the Replace field and enable regular
expression search by clicking on the . *
button.
((^[^\S$]*?(?=\S)(?:.*)+$)[\S\s]*?)^\2$(?:\n)?
.((^[^\S$]*?(?=\S)(?:.*)+$)[\S\s]*?)^\2$(?:\n)?
$1
in the Replace field.$1
Replace all
button multiple times.You'll know that all duplicate lines have been replaced when the regex has no matches and the text No results is shown.
Here is a short clip that demonstrates the process.
This approach removes the duplicate lines and preserves the order.
I've also written an article on how to remove the trailing spaces automatically in VS Code
You can learn more about the related topics by checking out the following tutorials: