清理包含域的巨大文本文件

Cleanup huge text file containing domain

我有一个数据库,其中包含以下事项中列出的域的日志:

.youtube.com
.ziprecruiter.com
0.etsystatic.com
0.sparkpost.com
00.mail.ne1.yahoo.com
00072e01.pphosted.com
00111b01.pphosted.com
001d4f01.pphosted.com
011.mail.bf1.yahoo.com
1.amazonaws.com

我将如何使用 powershell 或 grep 清理它们,尽管我更愿意使用 powershell,以便它们仅包含具有 .com 扩展名的根域并删除任何单词和 .在那之前。

我认为最好的方法是查询从右到左查找点并删除第二个点及其后面的任何内容。例如 1.amazonaws.com 这里我们删除右边的第二个点以及它后面的任何内容? 即

youtube.com
ziprecruiter.com
etsystatic.com
yahoo.com
pphosted.com
amazonaws.com

您可以使用String.Trim()方法清除前导和尾随点,然后使用正则表达式-replace运算符去除除顶级和二级域名之外的所有内容:

$strings = Get-Content database_export.txt

@($strings |ForEach-Object Trim '.') -replace '.*?(\w+\.\w+)$','' |Sort-Object -Unique

您可以使用 Get-Content, Split on "." using Split(), get the last two items with [-2,-1], then join the array back up using -join. We can then retrieve unique items using -Unique from Select-Object.

将每一行读入一个字符串数组
Get-Content -Path .\database_export.txt | ForEach-Object {
    $_.Split('.')[-2,-1] -join '.'
} | Select-Object -Unique

或使用 Select-Object -Last 2 获取最后两项,然后通过管道传输到 Join-String

Get-Content -Path .\database_export.txt | ForEach-Object {
    $_.Split('.') | Select-Object -Last 2 | Join-String -Separator '.'
} | Select-Object -Unique

输出:

youtube.com
ziprecruiter.com
etsystatic.com
sparkpost.com
yahoo.com
pphosted.com
amazonaws.com

这里还有一个方法。 [咧嘴一笑]

它的作用...

  • 创建要使用的字符串数组
    当准备好真正做到这一点时,删除整个 #region/#endregion 部分并使用 Get-Content 加载文件。
  • 遍历 $InStuff 字符串集合
  • 在点上拆分当前项目
  • 获取结果数组中的最后两项
  • 用点连接它们
  • 将新字符串输出到 $Results 集合
  • 在屏幕上显示

代码 ...

#region >>> fake reading in a text file
#    in real life, use Get-Content
$InStuff = @'
.youtube.com
.ziprecruiter.com
0.etsystatic.com
0.sparkpost.com
00.mail.ne1.yahoo.com
00072e01.pphosted.com
00111b01.pphosted.com
001d4f01.pphosted.com
011.mail.bf1.yahoo.com
1.amazonaws.com
'@ -split [System.Environment]::NewLine
#endregion >>> fake reading in a text file

$Results = foreach ($IS_Item in $InStuff)
    {
    $IS_Item.Split('.')[-2, -1] -join '.'
    }

$Results

输出...

youtube.com
ziprecruiter.com
etsystatic.com
sparkpost.com
yahoo.com
pphosted.com
pphosted.com
pphosted.com
yahoo.com
amazonaws.com

请注意,此代码要求字符串是或多或少有效的 URL。我可以想到以点结尾的无效的……那些会失败。如果您需要处理此类问题,请添加所需的验证代码。

另一个想法...如果文件很大 [数万个字符串],您可能需要使用 ForEach-Object 管道 cmdlet [如 RoadRunner 所示] 以节省 RAM速度的代价。