我遇到了邮件问题。我需要获取
[email protected]
和两个人之间的所有消息[email protected]
。
这file
:
From: [email protected]
to: [email protected]
<body of the message1>
From: [email protected]
to: [email protected]
<body of the message1>
From: [email protected]
to: [email protected]
<body of the message1>
From: [email protected]
to: [email protected]
<body of the message1>
From: [email protected]
to: [email protected]
<body of the message1>
我尝试使用以下内容sed
:
sed -n "/From: [Ss]omebody1/,/From: /p" inputfile > test.txt
结果,我收到了来自 someone1 的所有邮件并test.txt
归档。
sed
问题是:要获取某人 1 和某人之间的邮件,其结构应该是什么?
答案1
和sed
:
sed -n '/^From: [email protected]/{h;n;/^to: [email protected]/{H;g;p;:x;n;p;s/.//;tx}}' file
/^From: [email protected]/
:首先搜索From:
电子邮件地址h;
将该行存储在保留空间中。n;
加载下一行(该to:
行)。
/^to: [email protected]/
:搜索to:
电子邮件地址H;
将该行附加到保留空间。g;
将保持空间复制到模式空间。p;
打印图案空间。:x;
设置一个名为的标签x
。n;
加载下一行(电子邮件正文)p;
打印该行。s/.//
在该行进行替换(只替换一个字符)...tx
... 该t
命令可以检查替换是否成功(当行不为空时,如电子邮件正文的末尾)。如果是,则跳回标签x
并重复,直到出现空行,如果不是,则跳转到脚本末尾。
输出:
From: [email protected]
to: [email protected]
<body of the message1>
From: [email protected]
to: [email protected]
<body of the message1>
答案2
使用 awk:
awk '/From: [Ss]omebody1/{flag=1;next} \
/to\: person1/ {if (flag>0) {flag=2; print; next} else {flag=0; next}} \
/From/{flag=0} {if (flag==2){print NR,flag, $0}} ' input.txt
/From: [Ss]omebody1/{flag=1;next} \
匹配时将标志变量设置为 1,并跳过该行。/to\: person1/
如果标志为 1,则将其更新为 2,否则将其重置为 0。/From/{flag=0}
匹配时它会重置标志值。{if (flag==2){print NR, $0}}
如果 flag 为 2,它将打印电话号码和那条线。
改变的值person1
以获得不同的匹配。
使用的输入文件
From: [email protected]
to: [email protected]
<body of the message1>
From: [email protected]
to: [email protected]
<body of the message2>
From: [email protected]
to: [email protected]
<body of the message3>
From: [email protected]
to: [email protected]
<body of the message4>
From: [email protected]
to: [email protected]
<body of the message5>