How to sort dates in text file using Windows Batch

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To sort dates in a text file using a Windows Batch script, you can use the sort command with the /o option to specify the output file. Here's an example of how you can do it:

Suppose you have a text file named "dates.txt" with the following content:

yaml
2021-09-15
2021-10-01
2020-12-25
2022-02-14

You can create a batch script, for example, "sort_dates.bat" with the following content:

batch
@echo off
setlocal enabledelayedexpansion

rem Replace "dates.txt" with the path to your input file
set "inputFile=dates.txt"

rem Replace "sorted_dates.txt" with the path to your output file
set "outputFile=sorted_dates.txt"

rem Sort the dates in ascending order
sort "%inputFile%" /o "%outputFile%"

echo Dates sorted successfully!

Save the batch script and double-click it to run. After executing the script, the dates in the "dates.txt" file will be sorted in ascending order, and the sorted dates will be written to a new file named "sorted_dates.txt". The original "dates.txt" file remains unchanged.

After running the script, the "sorted_dates.txt" file will contain the following sorted dates:

yaml
2020-12-25
2021-09-15
2021-10-01
2022-02-14

Please note that the above script assumes that the date format in the "dates.txt" file is in the format "yyyy-MM-dd". If your date format is different, you may need to modify the script accordingly. Additionally, the sort command sorts dates in lexicographical order, so it may not work correctly for date formats that are not in the "yyyy-MM-dd" format. In such cases, you may need to use a more sophisticated script or a different tool to handle the date sorting.