2

I have a file with a bunch of dates of the form a/b/c, where a,b, and c are numbers of varying character length. However, I'd like to change every instance to read c/a/b.

I'm wondering if there is a command to use the "find and replace" functionality that can also use multiple wildcards?

I have not found a way to do this using the :s documentation.

6
:%s,\v(\d+)/(\d+)/(\d+),\3/\1/\2,g
  • s is the substitution command, the % before it means that all lines of the file will be considered.
  • , is the separator. It is common to choose / as the separator, but since there are slashes in the pattern and replacement, it is useful to choose another separator, so as to avoid escaping.
  • \v enables very magic mode, so that special symbols such as +() do not need to be escaped.
  • (\d+) is the a capture group, capturing digits.
  • g indicates that all matches in a line should be replaced, not only the first match.

The substitution is done by reordering the groups as \3/\1/\2.

Sample input before

01/02/2020 1111/123/21
12/11/1212 VIM 10/1/1
ABC

and after the command

2020/01/02 21/1111/123
1212/12/11 VIM 1/10/1
ABC

You can find more on the substitute command at :help :s.

| improve this answer | |
  • 2
    I think to get the ordering I was after, I had to end with \3/\1\2 but that pretty much gets it, easy enough to remove the lagging / on each occurance. THANK YOU SO MUCH! – Zim Aug 6 at 15:41
  • 1
    Sorry! I read it too fast, it should be correct now. Glad to help! – Quasímodo Aug 6 at 15:50
  • 1
    What is the purpose of the , after %s ? – guntbert Aug 7 at 11:45
  • 1
    @guntbert It is not so usual, you may be familiar with / instead. But "picket fences" would be required if we sticked with slashes: %s/\v(\d+)\/(\d+)\/(\d+)/\3\/\1\/\2/g. I have edited the answer to include that, check it out – Quasímodo Aug 7 at 12:09
  • 1
    @Quasímodo oh, of course - I am used to using other delimiters but the comma threw me :-/ – guntbert Aug 7 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.