gpt4 book ai didi

powershell-2.0 - 在文本文件中找到一个字符串并将其替换为父文件夹的名称

转载 作者:行者123 更新时间:2023-12-02 05:03:54 24 4
gpt4 key购买 nike

我有这个问题,我必须用它的父文件夹的名称替换所有文本文件中的字符串“121212”(例如,如果父文件夹名为“123456”,那么字符串“121212”应该替换为“123456” ")

我以为我想出了如何使用以下命令执行此操作:

PS E:\testenvironment> $parent=get-childitem -recurse | where {$_.FullName -match "[testenvironment]\\\d{6}$"} | foreach {$_.Name}
PS E:\testenvironment> $parent
123456
456789
654321
987654
PS E:\testenvironment> $files=get-childitem -recurse | where {$_.FullName -match "\\\d{6,6}\\AS400\\test3.txt$"} | foreach {$_.FullName}
PS E:\testenvironment> $files
E:\testenvironment\123456\AS400\test3.txt
E:\testenvironment\456789\as400\test3.txt
E:\testenvironment\654321\AS400\test3.txt
E:\testenvironment\987654\AS400\test3.txt
PS E:\testenvironment> foreach ($file in ($files)) {Get-Content "$file" | foreach-Object {$_ -replace "121212", "($name in ($parent))"} | set-content "$file"}

但我收到这条消息:

Set-Content : The process cannot access the file 'E:\testenvironment\123456\AS400\test3.txt' **because it is being used by another process**.
At line:1 char:127
+ foreach ($file in ($files)) {Get-Content "$file" | foreach-Object {$_ -replace "121212", "($name in ($parent))"} | set-content <<<< "$file"}
+ CategoryInfo : NotSpecified: (:) [Set-Content], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.SetContentCommand

(...我当然会收到每个 test3.txt 文件...)

我无法弄清楚如何将“当前内存”放入新变量中,以便可以用新数据覆盖文件(当前位于内存中)。

最佳答案

如果您所有的文本文件都在您发布的目录结构中,则以下内容将完成工作:

get-childitem $testEnvPath -recurse -filter "*.txt" | foreach{
$content = Get-Content $_.fullname
#To get the file's grandparent directory name ($_.fullname -split '\\')[-3]
$content -replace "121212", ($_.fullname -split '\\')[-3] |
set-content $_.fullname
}

请注意,要“移动”到内存中的下一个文件/目录,这些项目的枚举必须在 foreach 语句内部,而您在外部枚举它们。

希望对您有所帮助。

关于powershell-2.0 - 在文本文件中找到一个字符串并将其替换为父文件夹的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13778790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com