批量文件在从其他txt追加后对txt进行排序

时间:2014-03-25 06:42:09

标签: windows file sorting batch-file

我想要一个批处理文件,我可以将文本文件拖到(最好是一次多个文本文件)上,这将逐行读取每个文本文件,并将每一行添加到指定的目标文本文件。目标文本文件不包含任何重复的行,并将按字母顺序排序。源文件永远不会包含相同的行两次,但可能包含非字母数字字符,例如:{ - :_~!

示例:

A.TXT:

apple
banana
garbage carrot
{Elmer Fudd}

b.txt

1 tequila
2 tequila
3 tequila
garbage carrot
{Bugs Bunny}

之前的destination.txt:

{daffy duck}
floor
将a.txt和b.txt拖到批处理文件后

destination.txt:

{Bugs Bunny}
{daffy duck}
{Elmer Fudd}
1 tequila
2 tequila
3 tequila
apple
banana
floor
garbage carrot

我已经开始了:

@echo off
setlocal disabledelayedexpansion
set "sourcefile=%~1"
echo "%sourcefile%" > temp.txt
for /f "delims=;" %%F in (%sourcefile%) do (
    echo %%F>>temp.txt
)

del /q destination.txt
ren temp.txt destination.txt

它复制拖动到临时文件中的文件,但我无法弄清楚如何对其进行排序。 sort命令对我不起作用,它只是挂起程序。所有帮助表示赞赏。谢谢!

3 个答案:

答案 0 :(得分:0)

@echo off
setlocal enabledelayedexpansion
set "prev="
echo "%~1"
copy /y destination.txt+"%~1" temp.txt >nul

(    
for /f "delims=" %%F in ('sort temp.txt') do (
  if "!prev!" neq "%%F" echo(%%F
  set "prev=%%F"
)
)>destination.txt
del temp.txt

应该适合你(我没试过)

无需使用for /f处理新文件 - copy a+b c将a和b连接到c。 /y强制覆盖目标(如果已存在)。

然后处理每一行,回显从sort读取的行,如果此行与前一行不匹配 - 但“将字符串括在引号中”,以便批处理知道将字符串作为单个单元处理包含空格或其他分隔符。

(...echo ...)>file格式(重新)使用echo ed数据创建文件,而不是将数据发送到屏幕。

答案 1 :(得分:0)

另存为批处理文件。这是一个混合批处理/ jscript文件。文件处理/排序在批处理部分完成。然后,调用javascript部分以消除重复的行。

已编辑 - 要适应评论

@if (@This==@IsBatch) @then
@echo off
rem **** batch zone *********************************************************

    setlocal enableextensions disabledelayedexpansion

rem If there are no files, nothing to do
    if "%~1"=="" goto endProcess

rem Configure the output final file 
    set "outputFile=destination.txt"
    if not exist "%outputFile%" >"%outputFile%" break

rem Configure and initialize temporary file
    set "tempFile=%temp%\%~nx0.%random%%random%.tmp"
    find /v "" <"%outputFile%" >"%tempFile%"

rem Iterate over the file list sending output to temporary file and deleting input file
    for %%a in (%*) do (
        find /v "" <"%%a" >>"%tempFile%"
        rem del /q "%%a" 2>nul 
    )

rem Process temporary file into outpufile, sorting and eliminating duplicates    
    type "%tempFile%" | sort  | cscript //nologo //e:Javascript "%~f0" > "%outputFile%"

rem Cleanup    
    del /q "%tempFile%" 2>nul

:endProcess 
    endlocal
    exit /b

@end
// **** Javascript zone *****************************************************
    var stdin=WScript.StdIn, stdout=WScript.StdOut, previous=null, current;
    while (!stdin.AtEndOfStream){
        if (previous !== (current=stdin.ReadLine())) stdout.WriteLine(current);
        previous = current;
    };

答案 2 :(得分:0)

如果我理解你,那么这就足够了:

@echo off
:loop
   type "%~1" >>"c:\destination.txt"
   shift 
   if not "%~1"=="" goto :loop
sort < "c:\destination.txt" > "%temp%\random file.txt"
move "%temp%\random file.txt" "c:\destination.txt"