Linux Shell实现Base64解码去换行,筛选含指定词的XML
刚好碰到过类似的场景,给你整理几个用Python、Perl、awk实现的方案,都是一步搞定解码、合并换行、筛选的需求:
Python 实现
这个方案用Python标准库处理Base64解码,不需要额外安装依赖,稳定性很高:
import base64 import sys def main(): if len(sys.argv) < 2: print("请传入要筛选的目标词汇,用法:python script.py '目标词汇' < input.txt", file=sys.stderr) sys.exit(1) target_word = sys.argv[1] for line in sys.stdin: line = line.strip() if not line: continue try: # 解码Base64字符串,转为UTF-8文本 decoded_xml = base64.b64decode(line).decode('utf-8') # 移除XML中的所有换行/回车,让整个文档变成单行,方便后续筛选和获取完整内容 single_line_xml = decoded_xml.replace('\n', '').replace('\r', '') # 检查是否包含目标词汇 if target_word in single_line_xml: # 如果需要保留原始XML的换行格式,把下面的print改成print(decoded_xml)即可 print(single_line_xml) except: # 跳过解码失败的无效行 continue if __name__ == "__main__": main()
用法
- 把上面的代码保存为
filter_base64_xml.py - 运行命令:
cat your_input_file.txt | python filter_base64_xml.py "你要找的词汇"
Perl 实现
Perl的MIME::Base64模块处理Base64编码非常高效,适合处理大文件:
#!/usr/bin/perl use strict; use warnings; use MIME::Base64; # 检查是否传入目标词汇 die "请指定要筛选的目标词汇,用法:perl script.pl '目标词汇' input.txt\n" unless $ARGV[0]; my $target = $ARGV[0]; while (my $encoded_line = <>) { chomp $encoded_line; next unless $encoded_line; eval { # 解码Base64 my $decoded = decode_base64($encoded_line); # 移除所有换行符,转为单行 $decoded =~ s/\r?\n//g; # 检查包含关系,index比=~更快 if (index($decoded, $target) != -1) { print "$decoded\n"; } }; # 捕获解码错误,跳过无效行 }
用法
- 保存为
filter_base64_xml.pl,给执行权限:chmod +x filter_base64_xml.pl - 运行命令:
cat your_input_file.txt | ./filter_base64_xml.pl "你要找的词汇"
如果系统里没有MIME::Base64模块,用CPAN安装:cpan MIME::Base64
Awk 实现
Awk本身没有内置的Base64解码函数,所以我们借助系统的base64命令来完成解码,适合喜欢用awk的场景:
BEGIN { if (ARGC < 2) { print "用法:awk -f script.awk '目标词汇' input.txt" > "/dev/stderr" exit 1 } target = ARGV[1] # 移除第一个参数,让awk正常处理输入文件 ARGV[1] = "" } { # 调用base64解码当前行,忽略错误输出 cmd = "echo \"" $0 "\" | base64 -d 2>/dev/null" # 读取解码结果 if ((cmd | getline decoded) > 0) { # 移除所有换行/回车 gsub(/\r?\n/, "", decoded) # 检查是否包含目标词汇 if (index(decoded, target) != 0) { print decoded } } # 关闭命令管道,避免资源泄漏 close(cmd) }
用法
- 保存为
filter_base64_xml.awk - 运行命令:
awk -f filter_base64_xml.awk "你要找的词汇" your_input_file.txt
或者用管道:
cat your_input_file.txt | awk -v target="你要找的词汇" -f filter_base64_xml.awk
内容的提问来源于stack exchange,提问作者Gábor Lipták
相关产品推荐
相关产品推荐

