[英]Replace strings in text files with string literals and file names in powershell
我的Google Fu使我失敗了,因此,我很樂意為您解決此問題。 我的目錄中充滿了標記文件(擴展名.xft)。 我需要通過將字符串文字和文件名(不帶文件擴展名)添加到每個文件來修改這些文件。
例如,我目前有:
<headerTag>
<otherTag>Some text here </otherTag>
<finalTag> More text </finalTag>
我需要結束的是:
<modifiedHeaderTag>
<secondTag> filenameGoesHere </secondTag>
<otherTag>Some text here </otherTag>
<finalTag> More text </finalTag>
所以在這個例子中
"<modifiedHeaderTag>
<secondTag>"
將是我的第一個字符串文字(這是一個常量,將其插入到同一位置的每個文件中),
filenameGoesHere
將是變量字符串(每個文件的名稱),並且
"</secondTag>"
將是我的第二個常量字符串文字。
我能夠使用以下方法成功替換文本:
(Get-Content *.xft).Replace("<headerTag>", "<modifiedHeaderTag>")
但是,當我嘗試
(Get-Content *.xft).Replace("<headerTag>", "<modifiedHeaderTag> `n
<secondTag> $($_.Name) </secondTag>")
我剛收到一條錯誤消息。 用${$_.Name)
$($_.Name)
替換$($_.Name)
${$_.Name)
也無效。
我嘗試了其他方法,但是這種方法是我最接近成功的方法。 我將不勝感激。 這可能很簡單,由於對Powershell的缺乏經驗,我只是沒有看到任何東西,因此伸出援助之手會非常棒。
如果以上內容不夠清楚,我們很樂意提供更多信息,請告訴我。 感謝大家!
這是我的方法,假設您將所有XFT都放在一個文件夾中,並且想要將更新寫回到同一文件中:
$path = "C:\XFTs_to_Modify"
$xfts = Get-ChildItem $path -Include "*.xft"
foreach ($xft in $xfts) {
$replace = "<modifiedHeaderTag>
<secondTag> $($xft.Name) </secondTag>"
(Get-Content *.xft).Replace("<headerTag>", $replace) | Set-Content $xft.FullName -Force
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.