【问题标题】:compare lines and make new line out of matches比较行并从匹配项中创建新行
【发布时间】:2015-12-23 06:31:57
【问题描述】:

我有两个文件:

文件1:

Server A sent Mail with testuser1@testdom.com
Server A sent Mail with testuser2@testdom.com
Server B sent Mail with testuser3@testdom.com

文件2:

testuser1@testdom.com
testuser2@testdom.com
testuser3@testdom.com

例如,如果来自 file2 的电子邮件地址“testuser1@testdom.com”也在 file1 中,它应该将 file1 中的这一行附加到新文件 file3 中。 是否有可能两个有很多文件并一步将它们与 file2 进行比较?

这是我尝试过的,但它并不完全符合我的要求:

compare (cat $file1) (cat $file2) | Out-File $file3

还有这个:(只打印完全相同的行,但我部分需要它)

Get-Content $file1 | ForEach-Object {
    $file1_Line = $_
    Get-Content $file2 | Where-Object {$_.Contains($file1_Line)} |
        Out-File -FilePath $file3 -Append
}

【问题讨论】:

  • “它应该使用 file1 中的电子邮件地址或行创建一个新文件” - 你能澄清一下吗?
  • 例如,如果来自 file2 的电子邮件地址“testuser1@testdom.com”也在 file1 中,则应将此行从 file1 附加到 file3。

标签: string file powershell compare match


【解决方案1】:

如果我正确理解你的问题,你想要这样的东西:

$cInFile1 = "infile1.txt"
$cInFile2 = "infile2.txt"
$cOutFile = "outfile.txt"

# Reading files as collections on lines.
$cLines1 = Get-Content -Path $cInFile1
$cLines2 = Get-Content -Path $cInFile2

foreach ($sLine in $cLines1) {
    $sAddress = ($sLine -split ' ')[-1]
    if ($sAddress -in $cLines2) {
        $sLine | Out-File -FilePath $cOutFile -Append
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2016-08-12
    • 2021-11-18
    • 2023-02-23
    相关资源
    最近更新 更多