简体   繁体   English

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

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

Suppose we have a text file containing a fullpath of a files. 假设我们有一个包含文件全路径的文本文件。 And a second text file containing just the same files names but they can be preceeded with other characters. 第二个文本文件仅包含相同的文件名,但可以在其前面加上其他字符。

What I'd like to do is replace the filenames into second file with the fullpaths of them which are in the first text file. 我想做的是用第一个文本文件中的文件的完整路径将文件名替换为第二个文件。 How can that be done? 那怎么办?

For example; 例如;

In textFile1.txt you have got: 在textFile1.txt中,您具有: 在此处输入图片说明

In textFile2.txt you have got: 在textFile2.txt中,您具有: 在此处输入图片说明

I need a 3rd textFile3.txt like this (just made it manually for two of the files, but I need that for all of the files in the tree) 我需要这样的第3个textFile3.txt(只是手动为其中两个文件创建了它,但对于树中的所有文件都需要它) 在此处输入图片说明

Assuming the filenames are unique and the paths do not contain any of the filenames: 假设文件名是唯一的,并且路径不包含任何文件名:

# 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

Note: This is untestet, might contain bugs ;) 注意:这是取消测试,可能包含错误;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM