按文件中的列批量排序

时间:2012-04-16 08:37:46

标签: file sorting batch-file

我想知道是否有可能按列对文本文件进行排序。例如

我有aux1.txt这样的行

Name SecondName Grade

在shell中我可以这样做

sort -r -k 3 aux1  

它按第3列(等级)对文件进行排序。

批处理

sort /+3 < aux1.txt

在第3个字母后对文件进行排序。

我读了批处理的分类手册但没有结果。

3 个答案:

答案 0 :(得分:6)

您可以使用批处理文件编写自己的 sort-wrapper

您只需将列重新排序为临时文件,
对它进行排序并将其订购。 (几乎是显而易见的)

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
)

答案 1 :(得分:1)

对你来说可能为时已晚,但作为一般建议,你可以比创建一个临时文件简单得多。只需通过排序管理它:

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

请注意,它只是一个命令,只需在命令提示符处键入而不使用任何批处理文件(当然,必须减少%%)。

答案 2 :(得分:0)

虽然我非常喜欢Jeb的回答,但我一直在使用Chris LaRosa的 TextDB tools多年。

您可以对多个列进行排序,通过他的另一个工具(或任何其他CL工具)进行管道。有点老...