0

I am a beginner in batch scripting, trying to sort a text file and get the highest date in a year. Tried different options to sort text file based on date and remove duplicate lines, and finally get the highest period for each year into a different text file. But at first step, I am not able to sort by date in the text file. Please see below example.

Example: In file1, I have below lines

May-2017
Jul-2017
May-2017
Jan-2017
Sep-2018
Feb-2018

Output in file2 should be

Jul-2017
Sep-2018
Squashman
  • 13,649
  • 5
  • 27
  • 36
  • 3
    uh - batch doesn't know anything about dates. You either need a lot of code or (the help of) another programming language. – Stephan Aug 15 '18 at 20:07
  • _"Tried different options to sort text file based on period"_ This phrase have no sense! A _text file_ is always sorted in alphabetic order. You need a way to explicitly specify that the order you want is "Jan", "Feb", ..., "Dec" and then use such an order in the sort process. – Aacini Aug 15 '18 at 23:43
  • 1
    @Stephan: _"You need a lot of code"_. I don't think so... See my answer. **`;)`** – Aacini Aug 15 '18 at 23:52
  • The `SORT` command in Windows sorts in ascii text order. It knows nothing of numbers or dates. To sort your dates in correct order they would need to be in a YYYY-MM format. `2018-09` – Squashman Aug 16 '18 at 00:17
  • @Aacini "a lot of code" compared with `sort file.txt``. (I had something similar in mind, but no time to work it out) – Stephan Aug 16 '18 at 05:18

1 Answers1

1

This type of questions are usually downvoted and closed. StackOverflow is not a free code writing service. You must show an effort to write a solution for yourself first.

However I did an exception in this case, although I did not show any effort to explain the code...

@echo off
setlocal EnableDelayedExpansion

set "i=0"
for %%a in (Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) do (
   set /A "Mon[%%a]=i+=1"
   set "Mon[!i!]=%%a"
)

for /F "tokens=1,2 delims=-" %%a in (file1.txt) do (
   set /A "c=(Year[%%b]-Mon[%%a]>>31)+1,Year[%%b]=Year[%%b]*c+Mon[%%a]*^!c"
)

for /F "tokens=2,3 delims=[]=" %%a in ('set Year[') do echo !Mon[%%b]!-%%a
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • 1
    I especially like your two `set /a` lines `:)`. Would have been several lines in my solution. – Stephan Aug 16 '18 at 05:29