我写了这段代码来测试文本操作。对于从文本文件中读取的每一行,我都替换了制表符/返回/空格,然后检查该行是否包含“ SAAS”,并删除了A。然后将内容写入新文件。
问题在于,新文件仅包含我替换的行,并且在写入新文件时会删除原始文件中的其他任何文本行。
$Text = Get-Content -Path C:\Desktop\Phones\Phones_1.txt |
ForEach-Object {($_ -replace '\n','')} |
ForEach-Object {($_ -replace '\r','')} |
ForEach-Object {($_ -replace '\s','')} |
ForEach-Object {IF($_ | Select-String -Pattern 'SAAS'){$_ -replace 'SAAS','SAS'}}
$Text | Out-File 'C:\Desktop\Phones\phone2.txt'
需要任何帮助。
答案 0 :(得分:0)
这可能与您的Select-String
函数有关,我认为不需要该函数。另外,您可以将replace语句链接在一起,从而大大减少了保持代码序列化的需求。我认为这不会引起任何问题,但是您也不需要将ForEach-Object
块用大括号括起来。如下所示:
$Text = Get-Content -Path C:\Desktop\Phones\Phones_1.txt |
ForEach-Object { $_ -replace '\n','' -replace '\r','' -replace '\s','' -replace 'SAAS','SAS' }
$Text | Out-File 'C:\Desktop\Phones\phone2.txt'
答案 1 :(得分:0)
由于$Text
包含一行行,因此替换\r
的情况下,\n
毫无用处。
您应该通过edit提出问题来提供输入和预期输出的示例。
通过lookarounds 使用正则表达式
(Get-Content .\Phones_1.txt -raw) -replace '\r|\n|\s|(?<=SA)A(?=S)'|Set-Content Phone2.txt
从上述问题的全文中获得以下输出:
Iwrotethiscodetotestouttextmanipulation.ForeachlinereadfrommytextfileIreplacetabs /收益/位,thenIcheckifthelinecontainsthecarachters'SAS'andremoveanA.Ithenwritethecontenttoannewfile.TheissueisthatthenewfilecontainsonlylinesthatImadeareplacementonanddeletesanyotherlinesoftextfromtheorinalfilewhenwritingtothenewfile $文字=获取内容,路径C:\桌面\电话\ Phones_1.txt |的foreach对象{($的 -replace '\ n','')} | ForEach对象{($ -替换'\ r','')} | ForEach对象{($ -替换'\ s','' )} | ForEach-Object {IF($ | Select-String-Pattern'SAS'){$ _- replace'SAS','SAS'}} $ Text | Out-File'C:\ Desktop \ Phones \ phone2.txt'Anyhelp已申请。