powershell - Powershell设置内容替换字符串
问题描述
所以,我需要保存一个在文件上被替换的字符串。
我做错了什么,但我无法弄清楚,什么!
我的代码:
Get-ChildItem -Path C:\Users\user\Documents -Recurse -Include "*.txt" -File | Select-String -Pattern \b192\.168\.10\.2\b , \b192\.168\.10\.11\b -AllMatches -List | Foreach-Object { $_ -replace '\b192\.168\.10\.2\b', "DEV" -and $_ -replace '\b192\.168\.10\.11\b', "QUAL" | Set-Content $_}
并给我以下错误:
Set-Content : Could not open the alternate data stream '1:192.168.10.11' of the file 'C:\Users\user\Documents\result.txt'.
At line:1 char:323
+ ... place '\b192\.168\.10\.11\b', "QUAL" | Set-Content $_}
+
+ CategoryInfo : ObjectNotFound: (C:\Users\paulo....ents\result.txt:String) [Set-Content], FileNotFoundException
+ FullyQualifiedErrorId : GetContentWriterFileNotFoundError,Microsoft.PowerShell.Commands.SetContentCommand
Set-Content : Could not open the alternate data stream '1:192.168.10.11' of the file
'C:\Users\user\Documents\test.txt'
At line:1 char:323 ... place '\b192\.168\.10\.11\b', "QUAL" | Set-Content $_}
CategoryInfo : ObjectNotFound: (C:\Users\user\test.txt:String) [Set-Content], FileNotFoundException
FullyQualifiedErrorId : GetContentWriterFileNotFoundError,Microsoft.PowerShell.Commands.SetContentCommand
谢谢你的帮助!
解决方案
-and
运算符用于内部if
测试,例如if(this -and that)
.
您应该将双重替换操作从
$_ -replace '\b192\.168\.10\.2\b', "DEV" -and $_ -replace '\b192\.168\.10\.11\b', "QUAL"
进入
$_ -replace '\b192\.168\.10\.2\b', "DEV" -replace '\b192\.168\.10\.11\b', "QUAL"
另外,如果我正确理解了这个问题,您希望在文件中找到所有字符串替换,并且要获取所有内容,您需要-List
从 Select-String 中删除开关。
接下来,正如 Mathias 在他的回答中解释的那样,您需要使用Path
当前匹配中的属性来获取文件 FullName.
但是,如果您直接将其通过管道传递给 Set-Content,您将收到异常,因为该文件正在使用中,您无法写入同一个文件。
下面在同一路径中创建一个新文件,_replacements
并附加到文件名
# use '-Include' instead of '-Filter' if you need more file extensions to filter on
Get-ChildItem -Path 'C:\Users\user\Documents' -Recurse -Filter "*.txt" -File |
Select-String -Pattern '\b192\.168\.10\.2\b', '\b192\.168\.10\.11\b' -AllMatches |
Foreach-Object {
$file = '{0}_replacements{1}' -f [System.IO.Path]::GetFileNameWithoutExtension($_.Path),
[System.IO.Path]::GetExtension($_.Path)
$target = Join-Path -Path ([System.IO.Path]::GetDirectoryName($_.Path)) -ChildPath $file
$_ -replace '\b192\.168\.10\.2\b', "DEV" -replace '\b192\.168\.10\.11\b', "QUAL" |
Add-Content -Path $target
}
这会生成一个名为“C:\Users\user\Documents\test_replacements.txt”的文件
C:\Users\user\Documents\test.txt:4:DEV C:\Users\user\Documents\test.txt:7:QUAL
原始文件 'C:\Users\user\Documents\test.txt' 不会被更改。
推荐阅读
- java - 如何找到数组单词中的最后一个字母以查看下一个单词是否也以该字母开头?
- php - 在某个时期启动 php 脚本
- c# - 如何在 WPF 应用程序中使用 Prism 库上传文件?
- python - 在 django 中覆盖模型的管理表单
- osmnx - OSMNX 从图中删除建筑物
- angular - 具有正常 URL 的多个路由器出口
- javascript - 错误:内部错误:未知标识符
- react-native - 应用程序处于后台时的 OneSignal onReceived 侦听器操作
- python - 使用石榴:如何在隐马尔可夫模型中生成概率
- mysql - MySQL 结果为逗号分隔的 WHERE 子句