简体   繁体   English

用Powershell中的字符串文字和文件名替换文本文件中的字符串

[英]Replace strings in text files with string literals and file names in powershell

My google-fu has failed me, so I'd love to get some help with this issue. 我的Google Fu使我失败了,因此,我很乐意为您解决此问题。 I have a directory full of markup files (extension .xft). 我的目录中充满了标记文件(扩展名.xft)。 I need to modify these files by adding string literals and the filename (without the file extension) to each file. 我需要通过将字符串文字和文件名(不带文件扩展名)添加到每个文件来修改这些文件。

For example, I currently have: 例如,我目前有:

<headerTag>
<otherTag>Some text here </otherTag>
<finalTag> More text </finalTag>

What I need to end up with is: 我需要结束的是:

<modifiedHeaderTag>
<secondTag> filenameGoesHere </secondTag>
<otherTag>Some text here </otherTag>
<finalTag> More text </finalTag>

So in this example, 所以在这个例子中

"<modifiedHeaderTag>
<secondTag>"

would be my first string literal (this is a constant that gets inserted into each file in the same place), 将是我的第一个字符串文字(这是一个常量,将其插入到同一位置的每个文件中),

filenameGoesHere

would be the variable string (the name of each file) and, 将是变量字符串(每个文件的名称),并且

"</secondTag>"

would be my second constant string literal. 将是我的第二个常量字符串文字。

I was able to successfully replace text using: 我能够使用以下方法成功替换文本:

(Get-Content *.xft).Replace("<headerTag>", "<modifiedHeaderTag>")

However, when I tried 但是,当我尝试

(Get-Content *.xft).Replace("<headerTag>", "<modifiedHeaderTag> `n 
<secondTag> $($_.Name) </secondTag>")

I just got an error message. 我刚收到一条错误消息。 Replacing $($_.Name) with ${$_.Name) also had no effect. ${$_.Name) $($_.Name)替换$($_.Name) ${$_.Name)也无效。

I've tried other things, but this method was the closest that I had gotten to success. 我尝试了其他方法,但是这种方法是我最接近成功的方法。 I would appreciate any help that I can get. 我将不胜感激。 It's probably simple and I'm just not seeing something due to inexperience with Powershell, so a helping hand would be great. 这可能很简单,由于对Powershell的缺乏经验,我只是没有看到任何东西,因此伸出援助之手会非常棒。

If the above isn't clear enough, I'd be happy to provide more info, just let me know. 如果以上内容不够清楚,我们很乐意提供更多信息,请告诉我。 Thanks everyone! 感谢大家!

Here's my approach, assuming you have all of the XFT's in one folder and you want to write the updates back to the same file: 这是我的方法,假设您将所有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.

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