我有兩個檔案:FileA 和 FileB,它們幾乎相同。
這兩個檔案都有一個以////////// MAIN \\\\\\\\\\. 我需要從這一點替換整個內容,直到檔案結束。
所以流程高層看起來像:
- 在 FileA 中查找內容(以 開頭
////////// MAIN \\\\\\\\\\)直到檔案結尾并將其復制到剪貼板 - 在 FileB 中查找內容(以 開頭
////////// MAIN \\\\\\\\\\)直到檔案末尾,并將其替換為剪貼板中的內容
我該怎么做呢?
我知道它看起來像這樣(在網上找到),但我缺少可用于選擇文本直到檔案末尾的模式和邏輯:
# FileA
$inputFileA = "C:\fileA.txt"
# Text to be inserted
$inputFileB = "C:\fileB.txt"
# Output file
$outputFile = "C:\fileC.txt"
# Find where the last </location> tag is
if ((Select-String -Pattern "\</location\>" -Path $inputFileA |
select -last 1) -match ":(\d ):")
{
$insertPoint = $Matches[1]
# Build up the output from the various parts
Get-Content -Path $inputFileA | select -First $insertPoint | Out-File $outputFile
Get-Content -Path $inputFileB | Out-File $outputFile -Append
Get-Content -Path $inputFileA | select -Skip $insertPoint | Out-File $outputFile -Append
}
uj5u.com熱心網友回復:
你可以用兩行代碼做到這一點:
# first write the top part including the '////////// MAIN \\\\\\\\\\' from FileB to the new file
((Get-Content -Path "D:\Test\fileB.txt" -Raw) -split '(?<=/ MAIN \\ \r?\n)', 2)[0] | Set-Content -Path "D:\Test\fileC.txt" -NoNewline
# then append the bottom part excluding the '////////// MAIN \\\\\\\\\\' from FileA to the new file
((Get-Content -Path "D:\Test\fileA.txt" -Raw) -split '/ MAIN \\ \r?\n', 2)[-1] | Add-Content -Path "D:\Test\fileC.txt"
正則運算式詳細資訊:
(?<= # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
/ # Match the character “/” literally
# Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\ MAIN\ # Match the characters “ MAIN ” literally
\\ # Match the character “\” literally
# Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\r # Match a carriage return character
? # Between zero and one times, as many times as possible, giving back as needed (greedy)
\n # Match a line feed character
)
或者,如果檔案很大:
# first write the top part including the '////////// MAIN \\\\\\\\\\' from FileB to the new file
$copyThis = $true
$content = switch -Regex -File "D:\Test\fileB.txt" {
'/ MAIN \\ ' { $copyThis = $false; $_ ; break}
default { if ($copyThis) { $_ } }
}
$content | Set-Content -Path "D:\Test\fileC.txt"
# then append the bottom part excluding the '////////// MAIN \\\\\\\\\\' from FileA to the new file
$copyThis = $false
$content = switch -Regex -File "D:\Test\fileA.txt" {
'/ MAIN \\ ' { $copyThis = $true }
default { if ($copyThis) { $_ } }
}
$content | Add-Content -Path "D:\Test\fileC.txt"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434560.html
標籤:电源外壳
