Using Windows/DOS shell/batch commands, how do I take a file and only keep unique lines?

前端 未结 8 1300
刺人心
刺人心 2020-12-06 02:56

Say I have a file like:

apple
pear
lemon
lemon
pear
orange
lemon

How do I make it so that I only keep the unique lines, so I get:



        
8条回答
  •  时光取名叫无心
    2020-12-06 03:07

    @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"
    )
    

    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

提交回复
热议问题