如何用Bash移除文本文件中与指定列表不匹配的行?
实现文本文件中保留两字符串列表交集行的方法
你需要保留的是同时存在于两个字符串列表中的行(即交集),以下是几种实用的实现方式:
Python 脚本实现
适合跨平台使用,逻辑清晰易修改:
# 定义需要匹配的目标字符串集合(对应你的第二个列表) target_set = {'AppleRed', 'AppleGreen', 'PearBrown', 'PearGreen', 'BannanaYellow', 'BannanaGreen', 'KiwiGreen', 'KiwiBrown'} # 处理文件:读取输入,筛选后写入输出 with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile: for line in infile: stripped_line = line.strip() if stripped_line in target_set: outfile.write(line)
- 把目标列表转为集合是为了提升查找效率,尤其是当列表规模较大时
input.txt是包含第一个列表内容的文本文件(每行一个字符串),运行后结果会保存到output.txt
Linux/Unix 命令行(grep)
适合快速处理文件,无需编写脚本:
- 先把第二个列表的字符串写入
targets.txt,每行一个:
AppleRed AppleGreen PearBrown PearGreen BannanaYellow BannanaGreen KiwiGreen KiwiBrown
- 执行grep命令筛选:
grep -x -f targets.txt input.txt > output.txt
-f targets.txt:从指定文件读取匹配模式-x:强制整行完全匹配,避免出现部分匹配的错误结果- 结果会直接输出到
output.txt
Awk 实现
同样适用于命令行环境,处理大文件效率较高:
awk 'NR==FNR {target[$0]=1; next} target[$0]' targets.txt input.txt > output.txt
- 第一部分
NR==FNR {target[$0]=1; next}:读取targets.txt,将每个字符串存入数组target - 第二部分
target[$0]:读取input.txt,仅打印存在于target数组中的行
内容的提问来源于stack exchange,提问作者Stt4e
相关产品推荐
相关产品推荐

