naveencgr8
naveencgr8

Reputation: 341

Display parameters in reverse order

I need to create a batch file which will display on the screen up to 9 parameters, but displays them in reverse order. Name of the batch file is reverse11.bat

eg: C:\>REVERSE11.bat a b c d e <enter>
e d c b a REVERSE

I tried to do so like this, it kinda mess and didnt work. :(

SORT/R < %O > ANSWER
ECHO ANSWER

Whats wrong with it?

Upvotes: 0

Views: 1434

Answers (3)

Aacini
Aacini

Reputation: 67216

You must note that sort command Works on LINES, not WORDS! The Batch file below first divide the parameters in separate lines and store they in a temp file; the second part invoke sort /R on the file and collect its output lines in just one string:

@echo off
setlocal EnableDelayedExpansion
(for %%a in (%*) do echo %%a) > temp.txt 
set output=
for /F "delims=" %%a in ('sort /R ^< temp.txt') do set output=!output! %%a
echo %output:~1%
del temp.txt

Upvotes: 1

Nate Hekman
Nate Hekman

Reputation: 6657

SORT sorts lines, not words, so you'll need to put each parameter on its own line.

setlocal enabledelayedexpansion
echo %1> unsorted.txt
echo %2>> unsorted.txt
echo %3>> unsorted.txt
:: etc...

sort /r unsorted.txt > sorted.txt

At this point you could display sorted.txt if you're okay with them all being on separate lines:

type sorted.txt

But if you want to get them all back onto a single line you'll have to process the file like this:

for /f %%a in (sorted.txt) do (
    set out=!out! %%a
)
echo %out%

Upvotes: 1

Magoo
Magoo

Reputation: 80023

@ECHO OFF
SETLOCAL
SET reversed=%0
:loop
SET newparam=%1
IF NOT defined newparam ECHO %reversed%&GOTO :eof
SET reversed=%1 %reversed%
shift
GOTO loop

We start by setting the variable reversed to the value of the program name.

Set newparam to the value of the FIRST parameter (%1) If that parameter exists,add it to the FRONT of the accumulated string, then SHIFT to move the parameters to one position lower (%2 becomes %1, %3 becomes %2, etc.) and loop back until...

the %1 parameter does NOT exist (because they've all been SHIFTed out) so echo the accumulated string in reversed and finish the routine.

Upvotes: 0

Related Questions