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:
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.
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
The only way to stop an infinitely loop in Windows Batch Script is by either pressing Ctrl + C or by closing the program.
In a batch file, the @ symbol at the start of a line is the same as ECHO OFF applied to the current line only.
By default, /F breaks up the command output at each blank space, and any blank lines are skipped.
@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
Run PowerShell from the command prompt.
Assuming the items are in a file call fruits.txt
, the following will put the unique lines in uniques.txt
:
type fruits.txt | Sort-Object -unique | Out-File uniques.txt
In Windows 10 sort.exe
has a hidden flag called /unique
that you can use
C:\Users>sort fruits.txt
apple
lemon
lemon
lemon
orange
pear
pear
C:\Users>sort /unique fruits.txt
apple
lemon
orange
pear
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With