
我有一個文字文件,每行一個電子郵件地址。如何刪除每行的網域部分而不是 TLD 部分?在這裡,我們將 TLD 定義為字串中最後一個點字元之後的最後一個元素。
換句話說,樣本輸入:
[email protected]
[email protected]
[email protected]
[email protected]
期望的輸出:
foobar@org
john.smith@com
chunkylover69@dk
qwerty@uk
答案1
$ sed 's/@.*[.]/@/' file
foobar@org
john.smith@com
chunkylover69@dk
qwerty@uk
正規表示@.*[.]
式捕捉從線上@
到最後一個句點的所有內容。.
我們將其替換為@
.
答案2
使用perl
perl -pe 's/(@).*\.(.*)$/\1\2/' foo
或內聯
perl -i -pe 's/(@).*\.(.*)$/\1\2/' foo
例子
$ cat foo
[email protected]
[email protected]
[email protected]
[email protected]
$ perl -pe 's/(@).*\.(.*)$/\1\2/' foo
foobar@org
john.smith@com
chunkylover69@dk
qwerty@uk
正規表示式解釋
/(@).*\.(.*)$/
第一捕獲組 (
@
)@
@
字面匹配字符.*
匹配任何字元(換行符除外)量詞:
*
零次到無限次之間,盡可能多的次數,按需回饋[貪婪]\.
.
字面匹配字符第二捕獲組 (
.*
).*
匹配任何字元(換行符除外)量詞:
*
零次到無限次之間,盡可能多的次數,按需回饋[貪婪]$
斷言字串末尾的位置
答案3
使用awk
你可以這樣做
$awk '{ sub(/\@.*\./,"@"); print }' file
foobar@org
john.smith@com
chunkylover69@dk
qwerty@uk
使用sub
取代(尋找和取代),您可以搜尋模式並取代。