0

What's the way to sort a list of files, which is processed by a batch-file via sendTo-menu, eg:

myDir
  file_1.txt
  file_3.txt
  hello.world
  foo.bar

If I mark these files and call a batch file via sendTo-link to process those files, the order of the files seems to be random:

FOR %%A IN (%*) DO (set command=!command! %%A)
ECHO %command%

In some cases this shoud make no difference, but for merging for example, it does.

Something like using dir"*.sql ^| sort does not seem to work thus selected filenames are not considered.

Nico
  • 1,175
  • 15
  • 33
  • 1
    Well, the order depends on the "mood" of Windows Explorer. If the order is relevant for a certain task I would rather go for a list file (a text file containing paths to the files to be processed in the given order, one per line)... – aschipfl May 06 '20 at 11:59
  • Hmpf. I hoped to learn a solution to get the files sorted using the sendTo command. I don't want to create a file and reread it :( But thanks for your comment. I appreciate it! – Nico May 06 '20 at 12:17
  • 3
    You can of course let your batch script sort the items by certain criteria; for instance, alphabetic sorting: `@(for %%A in (%*) do @echo/%%~A) | sort`... – aschipfl May 06 '20 at 12:57
  • @aschipfl Thank you for you help. Could you tell me how to adjust `FOR %%A IN (%*) DO (set command=!command! %%A)`to achieve the sorting? I don't get it running this way. Sorry, I'm not that familiar with the batch commands. The code snippet you offered works like a charm, but the filenames can't be used for further processing. – Nico May 07 '20 at 00:58
  • Do you really need all arguments in a single line? The `for` loop stuff I suggested is just to put one argument per line, so `sort` can handle it; you can [redirect](https://ss64.com/nt/syntax-redirection.html) the output of `sort` into a temporary file and read this by [`for /F`](https://ss64.com/nt/for_f.html), in which you can reassemble the argument string as you already did... – aschipfl May 07 '20 at 01:48

1 Answers1

0
@echo off
setlocal

rem Sort args stored if 1st argument is /sort_args.
if "%~1" == "/sort_args" goto :sort_args

rem Store all arguments in a named variable.
set args=%*

rem Process sorted arguments.
for /f "delims=" %%A in ('cmd /c "%~f0" /sort_args') do (
    echo %%A
)
exit /b 0


:sort_args

rem Abort if no arguments.
if not defined args exit /b 0

rem Sort arguments.
(for %%A in (%args%) do @echo %%A) | sort
exit /b 0

If the original arguments do not have /sort_args as an argument, then this will store the arguments in args. The for /f loop will run this code again to sort the original arguments and echo the arguments back to the for /f loop for processing.

Can change /sort_args to something more unique if wanted.

michael_heath
  • 5,262
  • 2
  • 12
  • 22