【问题标题】:Powershell comparison of text file文本文件的Powershell比较
【发布时间】:2015-06-16 23:35:01
【问题描述】:

我只是想知道是否可以比较两个文本文件并检查它们之间是否存在差异?我的意思是这样的,

例如我有 text1.txt :

123
456
789
000

我有 text2.txt :

123,test,input,bake
789,input,cake,bun

预期输出:

456 does not exist in text2.txt
000 does not exist in test2.txt

我是这种语言的新手(Powershell)我只有这段代码可以获取两个文本文件的内容,但我不知道如何比较它。

$file1 = "C:\test\folder\test1.txt";
$file2 = "C:\test\folder\test2.txt";

$getfile1 = Get-Content $file1
$getfile2 = Get-Content $file2

【问题讨论】:

    标签: powershell readfile


    【解决方案1】:

    让你开始的东西:

    # $file1 will be an array with each element containing the line contents
    $file1 = get-content .\text1.txt
    
    # $file2 will be an array with each element containing the line contents just like $file1
    $file2 = get-content .\text2.txt
    
    # This splits each line of $file2 on the comma and grabs the first element and assigns it to the $file2FirstPart array.
    $file2FirstPart = $file2 | ForEach-Object { $_.Split(',')[0] }
    
    # This uses the Compare-Object cmdlet to compare the arrays.
    $comparision = Compare-Object -ReferenceObject $file1 -DifferenceObject $file2FirstPart -Passthru
    
    # This just displays the string you wanted to display for the comparison results
    $comparison | ForEach-Object { "$($_) does not exist in text file 2" }
    

    祝你学习 powershell 好运!

    【讨论】:

    • 我也在讨论将 % 更改为 ForEach-Object 并解释别名,因为用户是新用户.....
    • 谢谢大家的解释!我现在意识到 powershell 有多么强大:)
    • @Matt - 你说得对,我不应该使用别名开始,因为 OP 是新的,我会更新它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2013-11-28
    相关资源
    最近更新 更多