Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch sort by column in file

I wonder if there is any posibility to sort a text file by columns. For example

I have aux1.txt with rows like this

Name SecondName Grade

In shell i can do this

sort -r -k 3 aux1  

It sorts the file by the 3rd column(grade).

In batch

sort /+3 < aux1.txt

sorts the file after the 3rd letter.

I read the sort manual for batch but no results.

like image 981
vladCovaliov Avatar asked Apr 25 '26 03:04

vladCovaliov


2 Answers

You could write your own sort-wrapper with a batch file.

You only need to reorder the columns into a temporary file,
sort it and order it back. (nearly obvious)

REM *** Get the desired colum and place it as first column in the temporary file
setlocal DisableDelayedExpansion
(
    for /F "tokens=1-3 delims= " %%A in (aux1.txt) DO (
        set "par1=%%A"
        set "par2=%%B"
        set "par3=%%C"
        setlocal EnableDelayedExpansion
        echo(!par2! !par1! !par2! !par3!
        endlocal
  )
) > aux1.txt.tmp

REM ** Now sort the first colum, but echo only the rest of the line
for /F "usebackq tokens=1,* delims= " %%A in (`sort /r aux1.txt.tmp`) DO (
    echo(%%B
)
like image 132
jeb Avatar answered Apr 26 '26 16:04

jeb


May be too late for you but as a general advice you can do it much simpler than creating a temporary file. Just pipe it all through sort:

for /f "tokens=1-3" %%a in ('(for /f "tokens=1-3" %%x in (aux1.txt^) do @echo %%z %%x %%y^)^|sort') do echo %%b %%c %%a

Note, that it's a single command and can be used just by typing at command prompt without any batch file at all (have to reduce %%'s for that, of course).

like image 28
panda-34 Avatar answered Apr 26 '26 16:04

panda-34



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!