![](https://batch-file.net/wp-content/themes/cocoon-master/images/b-woman.png)
バッチファイルで
・テキストファイルをソートして、重複行を削除
できます!
![](https://batch-file.net/wp-content/themes/cocoon-master/images/b-woman.png)
バッチファイルから
・Power Shellのコマンドレットを実行
することで実現します!
コード
ここでは例として
・デスクトップ配下のテキストファイル「sample.txt」をソートして、重複行を削除
します。
![テキストファイル「sample.txt」](https://batch-file.net/wp-content/uploads/2022/11/bat_textfile_sort_unique_001.png)
![テキストファイル「sample.txt」の内容(ソートされていない、かつ重複行あり)](https://batch-file.net/wp-content/uploads/2022/11/bat_textfile_sort_unique_002.png)
@echo off
rem 対象ファイル
set targetFile=C:\Users\user\Desktop\sample.txt
rem PowerShellのコマンドレットを組み立て(昇順でソートかつ重複行を削除)
set psCommand="(Get-Content %targetFile%) | Sort-Object -Unique | Out-File -Encoding default %targetFile%"
rem PowerShellのコマンドレットを組み立て(降順でソートかつ重複行を削除)
rem set psCommand="(Get-Content %targetFile%) | Sort-Object -Descending -Unique | Out-File -Encoding default %targetFile%"
rem PowerShellのコマンドレットを実行
powershell -NoProfile -ExecutionPolicy Unrestricted %psCommand%
rem 実行結果を確認
if %errorlevel% == 0 (
echo 正常終了しました。戻り値:%errorlevel%
) else (
echo 異常終了しました。戻り値:%errorlevel%
)
echo.
pause
exit
実行結果
テキストファイルをソートして、重複行を削除できました。
![](https://batch-file.net/wp-content/uploads/2022/11/bat_textfile_sort_unique_003.png)
![実行結果②](https://batch-file.net/wp-content/uploads/2022/11/bat_textfile_sort_unique_005.png)
参考①
上記のコードは以下の記事を参考にして作成しました。
参考②
上記で使用した以下の詳細は、公式サイトをご確認ください。
●「Get-Content」コマンドレット
●「Sort-Object」コマンドレット
●「Out-File」コマンドレット