在 Windows 系统中重新创建此 Linux diff 命令的精确输出

问题描述 投票:0回答:1

我在尝试在 Windows 环境中重新创建以下 Linux 命令的输出时失去了理智:

diff --old-line-format='%L' --new-line-format='' --unchanged-line-format='' file1 file2 | grep -v '^$'

我无法安装任何东西,甚至无法安装Notepad++插件,因为它是企业服务器。 我只能使用 CMD 或 PowerShell (据我所知)

我得到的最接近的是以下Powershell“脚本”:

$file1 = Get-Content "file1.txt"
$file2 = Get-Content "file2.txt"

$only_in_file1 = $file1 | Where-Object {
    $_ -notin $file2
}

$only_in_file1

但它无法显示与我在 Linux 中得到的完全相同的输出。让我解释一下,

文件1:

#AK.70.1.1.5
ServerTokens Prod
Header always unset "X-Powered-By"
Header unset "X-Powered-By"
#AK.70.1.1.6
ServerSignature Off
AddServerHeader Off

#ServerTokens Prod
#ServerSignature Off
#AddServerHeader Off

文件2:

blah blah blah
durr durr durr
ServerTokens Prod
blah blah blah
durr durr durr
ServerSignature Off
AddServerHeader Off

预期输出(我在 Linux 中得到的结果):

#AK.70.1.1.5
ServerTokens Prod
Header always unset "X-Powered-By"
Header unset "X-Powered-By"
#AK.70.1.1.6
ServerSignature Off
AddServerHeader Off
#ServerTokens Prod
#ServerSignature Off
#AddServerHeader Off

实际输出(我从PowerShell得到的)

#AK.70.1.1.5
Header always unset "X-Powered-By"
Header unset "X-Powered-By"
#AK.70.1.1.6
#ServerTokens Prod
#ServerSignature Off
#AddServerHeader Off

你看,虽然我在 file1 中注释了 file2 行,并将它们粘贴到不同的位置,但它仍然认为它们没有不同。

我真的无法集中注意力在这个话题上。现在已经过去4个小时了。不是开玩笑。

欢迎任何想法!

powershell diff
1个回答
0
投票

尝试这个脚本:

# Read the contents of files and store it in the variables
$file1Content = Get-Content -Path "file1" -Raw
$file2Content = Get-Content -Path "file2" -Raw

# Split the contents of files into lines and store them in the variables
$lines1 = $file1Content -split "`n"
$lines2 = $file2Content -split "`n"

# Compare lines in file1 and file2, including equal lines and passing all input objects
$diff = Compare-Object -ReferenceObject $lines1 -DifferenceObject $lines2 -IncludeEqual -PassThru | Where-Object { $_.SideIndicator -eq "<=" }

# Filter the resulting lines to remove empty ones and display only the unique lines of file1
$diff | ForEach-Object { $_.InputObject } | Where-Object { $_ -ne "" }
© www.soinside.com 2019 - 2024. All rights reserved.