0

A file contains

03-01-2020 04-01-2021
03-02-2020 04-02-2021
03-03-2020 04-03-2021
03-04-2020 04-04-2021
03-05-2020 04-05-2021
03-06-2020 04-06-2021
03-07-2020 04-07-2021
03-08-2020 04-08-2021
03-09-2020 04-09-2021
03-10-2020 04-10-2021
03-11-2020 04-11-2021
03-12-2020 04-12-2021
03-13-2020 04-13-2021

How will I change it to (using regular expression)

20-03-01 21-04-01
20-03-02 21-04-02
20-03-03 21-04-03
20-03-04 21-04-04
20-03-05 21-04-05
20-03-06 21-04-06
20-03-07 21-04-07
20-03-08 21-04-08
20-03-09 21-04-09
20-03-10 21-04-10
20-03-11 21-04-11
20-03-12 21-04-12
20-03-13 21-04-13

Here is what I have tried:

s/^#\s\+\(.\{-}\):/  21-04-01 "\1":/
1
2

You just need to place some capture groups in the right place:

%s/\v(\d\d-\d\d)-\d\d(\d\d) (\d\d-\d\d)-\d\d(\d\d)/\2-\1 \4-\3/
  1. \v : Enable very magic mode to avoid having to escape all the parens.
  2. (\d\d-\d\d) : Capture the first month and day.
  3. -\d\d : Match the dash and first two digits of the year but don't capture them.
  4. (\d\d) : Capture the last two digits of the year.
  5. : Match the space.
  6. (\d\d-\d\d)-\d\d(\d\d) : Repeat the above for the second date.

Capture groups are inserted into the replacement using the \N notation. Just count from the left each left parens ( and that tells you which number to use to bring that group over.

There are some variations of this, too. The above is verbose but it's probably the easiest way to see what's going on. Here's a shorter version:

%s/\v(\d\d-\d\d)-\d\d(\d\d)/\2-\1/g

Here we use global flag to apply the pattern twice per line rather than double the pattern manually.

1
  • @BLACKHAT Please give some indication as to whether this solution works for you (and accept the answer if it does).
    – B Layer
    Nov 9 '20 at 12:42
1

An alternative solution using strptime/strftime to demonstrate expression substitution;

%s/[0-9-]\+/\=strftime('%y-%m-%d', strptime('%m-%d-%Y', submatch(0)))/g

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.