对乱序重列文本内容,有一个比较通用的思路:先在每行数据前插入随机数,然后,再用 sort 命令重新排列数据,重列时再去掉插入的随机数即可。
演示代码考虑了各种特殊情况:包括特殊符号、空行、以分号打头的行……,能处理的数据行数只受内存的限制,能处理的行长受 findstr 处理能力的限制(处理65535个字符长度的行绰绰有余),只是处理过程中会产生比原文件略大的临时文件:- @echo off
- cd.>tmp.txt
- for /f "delims=" %%i in ('findstr /n .* test.txt') do (
- set "str=%%i"
- setlocal enabledelayedexpansion
- set "str=!str:*:=!"
- >>tmp.txt echo !random!:!str!
- endlocal
- )
- cd.>result.txt
- for /f "delims=" %%i in ('sort tmp.txt') do (
- set "str=%%i"
- setlocal enabledelayedexpansion
- set "str=!str:*:=!"
- >>result.txt echo.!str!
- endlocal
- )
- del tmp.txt
- start result.txt
复制代码
再来个效率稍微高一点的:
- @echo off
- cd.>tmp.txt
- for /f "delims=" %%i in ('findstr /n .* test.txt') do (
- set "str=%%i"
- setlocal enabledelayedexpansion
- set "str=!str:*:=!"
- >>tmp.txt echo !random! !str!
- endlocal
- )
- cd.>result.txt
- for /f "tokens=1*" %%i in ('sort tmp.txt') do (
- set "str=%%j"
- setlocal enabledelayedexpansion
- >>result.txt echo.!str!
- endlocal
- )
- del tmp.txt
- start result.txt
复制代码
|