我遇到了郵件問題。我需要獲取 2 個人之間的所有訊息:
[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
結果我收到了某人的所有郵件並進行test.txt
歸檔。
問題是: 應該怎樣的結構sed
才能只取得someone1 和person 之間的郵件?
答案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>