[英]Powershell: Multiple replace and delete
我需要有關此腳本的幫助。 我已經慢慢走到了這一步,但目前需要幫助。
我需要一個腳本,該腳本會將文本從節的末尾移動到文件中的特定點,然后刪除移動的文本。 要移動的文本具有標記,位置也有標記。 移動后,我需要能夠刪除文本。 還需要對同一目錄中的多個txt文件進行處理。
例如:
Sample Input .txt
A;1;1;####; (#### is the location (1) marker)
B
B
B
====-1234 (==== is the find (1) marker)
A;1;1;####; (#### is the location (2) marker)
B
B
B
====-5678 (==== is the find (2) marker)
After processing
A;1;1;1234;
B
B
B
A;1;1;5678;
B
B
B
文本文件可以具有多個分組,就像這樣。 從上到下的每個分組都需要這樣做。 這是我到目前為止的內容,它只是移動文本而不會刪除。
$file = "C:\Users\NX07934\Documents\Projects\23045\Docs\SampleData\*.txt"
$old = "\####"
$find = Get-ChildItem $file -recurse| Select-String -pattern "====-*"
$split = $find.ToString().Split("-")
$new = $split[1]
get-childitem "C:\Dir" -recurse -include *.txt |
select -expand fullname |
foreach
{
(Get-Content $_) -replace $old,$new |
Set-Content $_
}
感謝您提供的所有幫助!
有什么幫助嗎?
$text =
@'
A;1;1;####;
B
B
B
====-1234
A;1;1;####;
B
B
B
====-5678
'@
$regex =
@'
(?ms)(.+?####;
.+?)
====-(\d+)
'@
([regex]::matches($text,$regex) |
foreach {
$_.groups[1].value -replace '####',($_.groups[2].value)
}) -join ''
A;1;1;1234;
B
B
B
A;1;1;5678;
B
B
B
編輯:-將其應用於文件集合:
$regex =
@'
(?ms)(.+?####;
.+?)
====-(\d+)
'@
Get-Childitem -Path C:\somedir -Filter *.txt |
foreach {
$Text = Get-Content $_ -Raw
([regex]::matches($text,$regex) |
foreach {
$_.groups[1].value -replace '####',($_.groups[2].value)
}) -join '' |
Set-Content $_.FullName
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.