本文目录导读:

使用Shell脚本(Linux/Mac)
#!/bin/bash # 输入文件: input.txt,输出文件: output.txt # 方法1:使用sort和uniq sort input.txt | uniq > output.txt # 或者更简洁的写法 sort -u input.txt > output.txt # 忽略大小写排序去重 sort -f -u input.txt > output.txt # 按数字排序去重(适用于数字列表) sort -n -u input.txt > output.txt
示例input.txt内容:
apple
banana
apple
cherry
banana
date
cherry
执行后的output.txt:
apple
banana
cherry
date
使用Python脚本
#!/usr/bin/env python3
# 脚本: sort_unique.py
def sort_and_unique(input_file, output_file, ignore_case=False):
"""
读取文件,排序去重后输出
"""
try:
with open(input_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
# 去除空白行和首尾空白
lines = [line.strip() for line in lines if line.strip()]
# 去重
if ignore_case:
seen = set()
unique_lines = []
for line in lines:
key = line.lower()
if key not in seen:
seen.add(key)
unique_lines.append(line)
else:
unique_lines = list(set(lines))
# 排序
if ignore_case:
unique_lines.sort(key=str.lower)
else:
unique_lines.sort()
# 写入输出文件
with open(output_file, 'w', encoding='utf-8') as f:
f.write('\n'.join(unique_lines))
print(f"处理完成!输入 {len(lines)} 行,输出 {len(unique_lines)} 行")
except FileNotFoundError:
print(f"错误:文件 {input_file} 不存在")
except Exception as e:
print(f"错误:{e}")
# 使用示例
if __name__ == "__main__":
sort_and_unique("input.txt", "output.txt")
更高级的Python版本(支持多种选项)
#!/usr/bin/env python3
# 脚本: advanced_sort_unique.py
import argparse
import sys
def process_file(input_file, output_file, **kwargs):
"""
高级文件处理函数
"""
options = {
'ignore_case': kwargs.get('ignore_case', False),
'numeric_sort': kwargs.get('numeric_sort', False),
'reverse': kwargs.get('reverse', False),
'unique_only': kwargs.get('unique_only', False),
'column': kwargs.get('column', None)
}
try:
with open(input_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
# 处理每一行
processed_lines = []
for line in lines:
line = line.strip()
if line: # 忽略空行
processed_lines.append(line)
# 去重
if options['unique_only']:
seen = set()
unique_lines = []
for line in processed_lines:
key = line.lower() if options['ignore_case'] else line
if key not in seen:
seen.add(key)
unique_lines.append(line)
else:
unique_lines = processed_lines
# 排序
def sort_key(line):
if options['column']:
parts = line.split()
if options['column'] <= len(parts):
key = parts[options['column'] - 1]
else:
key = line
else:
key = line
if options['ignore_case']:
key = key.lower()
if options['numeric_sort']:
try:
return float(key)
except ValueError:
return float('inf') # 非数字排在最后
return key
unique_lines.sort(key=sort_key, reverse=options['reverse'])
# 写入输出
with open(output_file, 'w', encoding='utf-8') as f:
f.write('\n'.join(unique_lines) + '\n')
print(f"处理完成:{len(processed_lines)} 行 → {len(unique_lines)} 行")
except Exception as e:
print(f"错误:{e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='文件内容排序去重工具')
parser.add_argument('input', help='输入文件路径')
parser.add_argument('output', help='输出文件路径')
parser.add_argument('-i', '--ignore-case', action='store_true',
help='忽略大小写')
parser.add_argument('-n', '--numeric-sort', action='store_true',
help='按数字排序')
parser.add_argument('-r', '--reverse', action='store_true',
help='反转排序结果')
parser.add_argument('-u', '--unique', action='store_true',
help='去重(默认启用)')
parser.add_argument('-c', '--column', type=int,
help='按指定列排序(从1开始计数)')
args = parser.parse_args()
process_file(
args.input,
args.output,
ignore_case=args.ignore_case,
numeric_sort=args.numeric_sort,
reverse=args.reverse,
unique_only=args.unique,
column=args.column
)
使用示例:
# 基本用法 python3 advanced_sort_unique.py input.txt output.txt # 忽略大小写 python3 advanced_sort_unique.py input.txt output.txt -i # 按第二列排序 python3 advanced_sort_unique.py input.txt output.txt -c 2 # 反向排序 python3 advanced_sort_unique.py input.txt output.txt -r
使用Windows批处理(CMD)
@echo off
REM 脚本: sort_unique.bat
set "input_file=%~1"
set "output_file=%~2"
if "%input_file%"=="" (
echo 请指定输入文件
exit /b 1
)
if "%output_file%"=="" set "output_file=output.txt"
sort < "%input_file%" > temp_sorted.txt
findstr /v "^$" temp_sorted.txt > temp_nonempty.txt
sort temp_nonempty.txt | findstr /v /g:temp_sorted.txt > nul 2>&1
REM 使用PowerShell实现去重
powershell -Command "Get-Content '%input_file%' | Where-Object {$_.Trim() -ne ''} | Sort-Object -Unique | Set-Content '%output_file%'"
echo 处理完成!
del temp_sorted.txt temp_nonempty.txt 2>nul
使用PowerShell脚本
# 脚本: sort_unique.ps1
param(
[Parameter(Mandatory=$true)]
[string]$InputFile,
[Parameter(Mandatory=$false)]
[string]$OutputFile = "output.txt",
[switch]$IgnoreCase,
[switch]$NumericSort
)
try {
$content = Get-Content $InputFile -ErrorAction Stop
# 去除非空行
$content = $content | Where-Object { $_.Trim() -ne '' }
# 排序和去重
if ($NumericSort) {
$result = $content | Sort-Object {[int]$_} -Unique
}
elseif ($IgnoreCase) {
$result = $content | Sort-Object -CaseSensitive -Unique
}
else {
$result = $content | Sort-Object -Unique
}
# 输出结果
$result | Set-Content $OutputFile
Write-Host "处理完成!$($content.Count) 行 → $($result.Count) 行"
}
catch {
Write-Error "错误:$_"
exit 1
}
性能优化建议
对于大文件处理,可以考虑以下优化:
# 大文件处理的优化版本
def process_large_file(input_file, output_file):
"""处理大文件的优化方法"""
import os
# 使用临时文件分批处理
temp_files = []
chunk_size = 1000000 # 100万行为一批
with open(input_file, 'r', encoding='utf-8') as f:
chunk = []
for line in f:
chunk.append(line.strip())
if len(chunk) >= chunk_size:
# 处理当前批次
chunk = sorted(set(chunk))
temp_name = f"temp_{len(temp_files)}.txt"
with open(temp_name, 'w', encoding='utf-8') as tf:
tf.write('\n'.join(chunk))
temp_files.append(temp_name)
chunk = []
# 处理最后一批
if chunk:
chunk = sorted(set(chunk))
temp_name = f"temp_{len(temp_files)}.txt"
with open(temp_name, 'w', encoding='utf-8') as tf:
tf.write('\n'.join(chunk))
temp_files.append(temp_name)
# 合并所有临时文件
all_lines = []
for temp_file in temp_files:
with open(temp_file, 'r', encoding='utf-8') as f:
all_lines.extend(f.readlines())
os.remove(temp_file)
# 最终排序去重
unique_sorted = sorted(set(line.strip() for line in all_lines if line.strip()))
with open(output_file, 'w', encoding='utf-8') as f:
f.write('\n'.join(unique_sorted))
选择哪种方法取决于你的操作系统、文件大小和具体需求,对于大多数日常使用,Shell脚本(Linux/Mac)或PowerShell(Windows)就足够了;对于更复杂的需求,Python提供了最大的灵活性。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播