powershell - 在 Powershell 脚本中替换文本文件中的某些字符
问题描述
我有一个带有文本示例的文本文件:
+ Starting at line 0 $/A/B/C/Demo\Demo.sln
+ class string foo{
+ return "a\b";
+ }
我想将 \ 斜杠替换为 / 的路径。但它应该改变代码其他部分的\。为此,我必须使用 Powershell。预期代码:
+ Starting at line 0 $/A/B/C/Demo/Demo.sln
+ class string foo{
+ return "a\b";
+ }
解决方案
一种解决方案是在文件中包含至少一个“\”字符的每个字符串上使用Test-Path $string -IsValid
函数(此处'.*\\.*'
的文档),为此,您可以将文件中的文本拆分为空格并检查哪个结果字符串与正则表达式匹配.
结果可能是这样的:
$text = Get-Content -Path 'C:\...\data.txt'
$text -split '\s' | ForEach-Object {
#find strings with \ only
if($_ -match '.*\\.*') {
#if the string is like a path
if(Test-Path $_ -IsValid) {
#replace \ with /
$replace = $_ -replace '\\','/'
#replace path string with fixed path (note: [regex]::escape(...) is necessary to avoid using regex in this replace, because $_ contains some characters like \ end similar)
$text = $text -replace [regex]::escape($_), $replace
}
}
}
$text > 'C:\...\result.txt'
推荐阅读
- objective-c - NSSet 不包含对象,即使它们相等
- twitter - 如何使用 Twitter API 提取手动注释的推文?
- python - Python sqlite3 数据库包装器中需要游标对象吗?
- sql - 如何更改“WHERE startdate >= date”子句的值并获取一系列日期的数据?
- database - 达到时间戳时的 Postgresql 触发器
- mongodb - 我想使用 feathersJS 将图像从 react-native 上传到 mongoDB
- python - 如何将具有相同键的字典值合并为字典列表中的一个?
- java - 如何添加在带引号的 Thymeleaf 问题中
- typescript - 推断函数的参数类型
- ios - 在 Xcode 中将 Swift Playground 代码“移植”到应用程序的问题