比较两个文本文件并替换 powershell 中包含常用词的行

Compare two text files and replace the lines containing common words in powershell

假设我们有一个包含文件完整路径的文本文件。第二个文本文件只包含相同的文件名,但它们前面可以有其他字符。

我想做的是用第一个文本文件中的完整路径将文件名替换到第二个文件中。怎么做到的?

例如;

在 textFile1.txt 你有:

在 textFile2.txt 你有:

我需要第三个 textFile3.txt 像这样(只是为其中两个文件手动制作,但我需要为树中的所有文件制作)

假设文件名是唯一的并且路径不包含任何文件名:

# Read files
$File1 = Get-Content <file1>
$File2 = Get-Content <file2>

# Process each line
Foreach ($Line in $File1) {
    # Get only the filename for current line
    $FileName = $Line.Split("\")[-1]
    # Replace filename in file2 with the entire line of file1
    $File2 = $File2 -replace $Filename,$Line
}
# Write new content to file2
Set-Content -Path <file2> -Value $File2

注意:这是未测试的,可能包含错误;)