【问题标题】:Why does this code only output lines that I made a replacement on?为什么这段代码只输出我做了替换的行?
【发布时间】:2019-10-05 03:49:16
【问题描述】:

我编写了这段代码来测试文本操作。对于从我的文本文件中读取的每一行,我替换制表符/返回/空格,然后检查该行是否包含字符“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'

如有任何帮助,我们将不胜感激。

【问题讨论】:

    标签: powershell replace


    【解决方案1】:

    这可能与您的Select-String 函数有关,我认为它不需要存在。此外,您可以将替换语句链接在一起,从而大大减少了继续管道代码的需要。我认为这不会导致任何问题,但您也不需要将 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'
    

    【讨论】:

      【解决方案2】:

      由于$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-Object{($-replace'\r','')}|ForEach-Object{($-replace'\s','' )}|ForEach-Object{IF($|Select-String-Pattern'SAS'){$_-replace'SAS','SAS'}}$Text|Out-File'C:\Desktop\ Phones\phone2.txt'Anyhelpisappriciated.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-05
        • 1970-01-01
        • 2015-04-23
        • 1970-01-01
        • 2013-01-24
        • 1970-01-01
        • 2022-06-28
        • 2018-08-09
        相关资源
        最近更新 更多