我已经搜索了包括在StackOverFlow在内的所有内容,但似乎找不到我需要帮助的解决方案。这是我的问题。
可以说,在 File1.txt 中,我有以下内容(每行之间没有空格)
\\Serv02\LOC6\Client\726C30\032383\2200018023.pdf
\\Serv02\LOC6\Client\726C30\032383\2200718091.pdf
\\Serv02\LOC6\Client\726C30\030684\2300309040.pdf
\\Serv02\LOC6\Client\726C30\031274\2300429971.pdf
File2.txt 将具有相同的信息,但是,我需要在每个
1
的前面添加一个.pdf
(在file2.txt中)例:
\\Serv02\LOC6\Client\726C30\032383\22000180231.pdf
我可以使用RegEx语句轻松更新file2.txt,但是它只是基于该RegEx语句更新内容。
File2.txt中将比file1.txt中包含更多数据(更多的确切信息类型)。我只需要更新
1
之前添加的.pdf
中的file2.txt,这取决于file1.txt中的内容这是我正在使用的代码,但是您可以看到它根本不读取file1.txt,我只是使用RegEx语句来更新file2.txt,在.pdf之前添加1(下面的代码可以添加.pdf之前的1,但我没有遍历file1.txt)
clear-host
set-location c:\temp
$File = "C:\Temp\file1.txt"
$FileZ = "C:\Temp\file2.txt"
$File2 = (Get-ChildItem $fileZ) | Select -ExpandProperty BaseName
$regex01 = '(\\Serv02\LOC6\Client\726C30\\d{1,6}\\d{1,10})(.pdf)$'
get-content $fileZ | % { $_ -replace $regex01, '${1}1${2}' -join "`r`n" } | out-file -Encoding default "c:\Temp\$File2.txt"
start-sleep -Seconds 2
$NewMRC = Get-ChildItem "$file2.txt" | Select -ExpandProperty Name
Get-ChildItem $NewMRC | rename-item -NewName {$_.Name -replace ".txt",".MRC2"}
如果file1.txt的另一行与正则表达式不匹配,如上所示,则file2.txt不会用该行更新
\\Serv03\LOC7\Client\780D30\031456\8675309123.pdf
我希望我已经解释得足够好了。我不是PowerShell的新手,但我还不是专家。非常感谢您的协助。
最佳答案
我修改了您的代码,如下所示。该方法是读取File1.txt
的内容并将其存储在变量中。然后,在File2.txt
的每一行上进行迭代,以针对正则表达式以及该行是否出现在file1内容中进行检查。如果是,则将其替换为您想要的任何内容。在追加模式下将其输出到.tmp
文件。处理完File2.txt
中的所有行后,将其替换为.tmp
文件。
clear-host
set-location c:\temp
$File = "file1.txt"
$FileZ = "file2.txt"
# PS2
$File1 = get-content $File | Out-String
# PS3
# $File1 = get-content $File -Raw
$File2 = (Get-ChildItem $fileZ) | Select -ExpandProperty BaseName
if( test-path "$File2.tmp" ) { remove-item "$File2.tmp" }
$regex01 = '(\\\\Serv02\\LOC6\\Client\\726C30\\\d{1,6}\\\d{1,10})(.pdf)$'
get-content $fileZ |% {
$line = $_
$find = $line -replace '\\','\\'
if ( ($line -match $regex01) -AND ( $File1 -match $find ) ) {
$line -replace $regex01,'${1}1${2}' -join "`r`n"
} else {
$line
}
} | out-file "$File2.tmp" -append
remove-item "$File2.txt"
rename-item "$File2.tmp" "$File2.txt"
#start-sleep -Seconds 2
#$NewMRC = Get-ChildItem "$file2.txt" | Select -ExpandProperty Name
#Get-ChildItem $NewMRC | rename-item -NewName {$_.Name -replace ".txt",".MRC2"}
笔记:
$find = $line -replace '\\','\\'
:我们将双反斜杠\
替换为单个反斜杠\\
。但是,在-replace
的第一个参数中,必须将其转义,而在第二个参数中,则不能将其转义。因此,即使它们看起来相同,它们的解释也有所不同。 关于regex - PowerShell-如何基于另一个文件中的内容更新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649935/