Skip to content

Instantly share code, notes, and snippets.

@mendeza
Last active October 4, 2022 11:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mendeza/c1b161f6f0627094f7d74be8a9ee34c9 to your computer and use it in GitHub Desktop.
Save mendeza/c1b161f6f0627094f7d74be8a9ee34c9 to your computer and use it in GitHub Desktop.
Vim Sort with RegEx

Vim Sort with RegEx

Vim Manual

See :help :sort.

:[range]sor[t][!] [b][f][i][n][o][r][u][x] [/{pattern}/]

When /{pattern}/ is specified and there is no [r] flag the text matched with {pattern} is skipped, so that you sort on what comes after the match.

Example

  • You have a list of URLs to sort by domain name, each on a separate line.
  • The protocols are mixed http and https, moreover some URLs have www. and others do not. You wish to sort only by meaningful domain.
  • In (Neo)Vim Visual mode, select the list, invoke sort, and condition it on a regular expression.
:'<,'>sort /https\?:\/\/\(www\.\)\?/
" or even:
:'<,'>sort /ps\?:\/\/\(www\.\)\?/

Given this:

1. <http://x>
1. <https://bb>
1. <https://www.ba>
1. <http://www.a>

The effect is this:

1. <http://www.a>
1. <https://www.ba>
1. <https://bb>
1. <http://x>
@toraritte
Copy link

Thank you so much for the quoting from :help :sort - was trying to sorting URLs but kept forgetting to specify r at the end, and the results made no sense, driving me crazy...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment