使用windows / dos shell / batch命令,如何获取文件,并且只保留唯一的行? [英] Using windows/dos shell/batch commands, how do I take a file and only keep unique lines?
问题描述
说我有一个档案:
apple
pear
lemon
lemon
pear
orange
lemon
如何制作我只保留唯一的行,所以我得到:
How do I make it so that I only keep the unique lines, so I get:
apple
pear
lemon
orange
我可以修改原始档案或建立新档案。
I can either modify the original file or create a new one.
我认为有一种方法来扫描原始文件一次一行,检查该行是否存在于新文件,然后附加,如果没有。我不在这里处理真正的大文件。
I'm thinking there's a way to scan the original file a line at a time, check whether or not the line exists in the new file, and then append if it doesn't. I'm not dealing with really large files here.
推荐答案
@echo off
setlocal disabledelayedexpansion
set "prev="
for /f "delims=" %%F in ('sort uniqinput.txt') do (
set "curr=%%F"
setlocal enabledelayedexpansion
if "!prev!" neq "!curr!" echo !curr!
endlocal
set "prev=%%F"
)
它的作用:首先对输入进行排序,然后依次排序,只有当前行不同时才输出到前一个。它可以更简单,如果不需要处理特殊字符(这就是为什么 setlocal / endlocal
用于)。
它只是回显线 stdout
,如果你想写入文件do(假设你命名为 myUniq.bat
) myUniq>> output.txt
What it does: sorts the input first, and then goes though it sequentially and outputs only if current line is different to previous one. It could have been even simpler if not for need to handle special characters (that's why those setlocal/endlocal
are for).
It just echoes lines to stdout
, if you want to write to file do (assuming you named your batch myUniq.bat
) myUniq >>output.txt
这篇关于使用windows / dos shell / batch命令,如何获取文件,并且只保留唯一的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!