2017-03-16 107 views
0

我收到了這個電子郵件地址列表。
我想刪除所有域擴展名。

Input.csv
[email protected]
[email protected]
[email protected]
[email protected]

應導致:
PowerShell:刪除電子郵件列表中的域名擴展

Output.csv
john @ email
阿爾伯特@郵件
人@ hotmail的
commadore @ gmail的

如果我使用此代碼...

$Sourcefile = 'C:\PS\Input.csv' 
$Output = 'C:\PS\Output.csv' 

(Get-Content $Sourcefile) | Foreach-Object { 
$_ -replace '.com', ''` 
    -replace '.co.uk', ''` 
    -replace '.nl', ''` 
    -replace '.al', '' 

} | Set-Content $Output 


..我得到:

Output.csv
john @ email
bert @ mail - (al被刪除)
人@ hotmail的
馬度爾@ gmail的 - (COM被刪除)

任何人能幫助我們嗎?

回答

0

神仙所指出的,你需要知道你的正則表達式的元字符,如.

我想刪除所有域的擴展。

如果是這樣的話,那麼你不需要在你想要刪除的每一箇中輸入。你應該能夠在包括最後一段時間後刪除所有字符。

由於-replace是你做一個數組運算符不需要使用ForEach-Object

(Get-Content $Sourcefile) -replace "(@.+?)\..*$",'$1' | Set-Content $Output 

包括「@」後,將匹配一切。它只用「@」代替,第一個時間段之前是什麼。

如果你真的想要替換某些域名,你最好保留一個字符串數組,並用它構建一個正則表達式替換字符串。使更改變得更容易,代碼將保持清潔。

$suffixesToRemove = "com","co.uk","nl","al" 
$regex = "\.($(($suffixesToRemove|ForEach-Object{[regex]::Escape($_)}) -join "|"))$" 
(Get-Content $Sourcefile) -replace $regex | Set-Content $Output 

計算的正則表達式的字符串應該是這樣的

\.(com|co\.uk|nl|al)$ 

所以它使用了交替組元charaters逃脫。

+0

謝謝! :)超級開心:) – Hogne

2

-replace函數使用正則表達式。在正則表達式中,小數點表示除換行符以外的任何字符。你只需要用\就可以逃脫你的工作。

像這樣:

(Get-Content $Sourcefile) | Foreach-Object { 
$_ -replace '\.com$', ''` 
    -replace '\.co\.uk$', ''` 
    -replace '\.nl$', ''` 
    -replace '\.al$', '' 

} | Set-Content $Output 

按@ GVEE的評論添加結束繩錨$應該讓即使[email protected]提供它的工作。

+0

這種方法在多種情況下都不會失敗,例如'some.alternate @ emailaddress.com' =>'someternate @ emailaddress' – gvee

+0

是的。複用電子郵件地址非常困難。而且我很確定告訴OP他們正在處理RegEx會將他們指向正確的方向。 – Fairy

+1

@gvee好的,我被製造了。一個簡單的'$'應該可以解決你的情況。 – Fairy