以下是wrong但实现了你似乎要求的内容。
subj=$(sed -n '/^Subject: PD *//!d;p;q;/^$/q' "$f")
这样做的问题是,它在普通情况下会成功,但当您有 MIME RFC2047 编码时会失败Subject:
标头,并且(更简单地)当Subject:
标题跨越一行以上。
我会用一种稍微现代的编程语言来解决这个问题。这并不完全是一句简单的话,但使用 Python 就足够简单了。
subj=$(./emailsubj.py "$f")
where emailsubj.py
包含或多或少类似的东西
#!/usr/bin/env python
from email.parser import Parser
from email.header import Header, decode_header
from sys import argv
for filename in argv[1:]:
with open(filename, 'rb') as handle: # handle file not found etc?
message = Parser().parse(handle)
try:
subj = ''.join([frag.decode(enc) if enc else frag
for frag, enc in decode_header(message['subject'])])
except HeaderParseError, UnicodeDecodeError:
subj = message['subject'] # maybe warn about error?
print(subj)
(记得chmod +x emailsubj.py
, 明显地。)
这将检索整个Subject:
header,对于模块化工具来说似乎是一个很好的设计。如果您想在提取标头后删除前缀,shell 有简单的功能参数扩展 https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html正是这样做的。例如,
echo "${subj#PD: )"
显示的值$subj
带有任何前缀PD:
从值的前面删除。
这是一个 Python 3 版本,由Xlea /users/2473926/xlea in a 提议的编辑 /review/suggested-edits/23544495然而,它违反了一般的堆栈溢出准则,因此在我将其合并到这个答案之前被拒绝了。
#!/usr/bin/env python3
from email.parser import BytesParser
from email.header import Header, decode_header
from email.errors import HeaderParseError
from sys import argv
for filename in argv[1:]:
with open(filename, 'rb') as handle: # handle file not found etc?
message = BytesParser().parse(handle)
try:
subj = ''.join([
frag.decode(enc if enc else "utf-8")
if isinstance(frag, bytes) else frag
for frag, enc in decode_header(message['subject'])])
except (HeaderParseError, UnicodeDecodeError): # maybe warn about error?
subj = message['subject']
subj = subj.decode("utf-8") if isinstance(subj, bytes) else subj
print(subj)