Powershell如何在特定字符串后添加新行

Powershell如何在特定字符串后添加新行,powershell,newline,Powershell,Newline,我对脚本非常陌生。我正在尝试解决一个问题,我正在研究windows批处理和powershell。我发现了这个,但我不知道为什么它不起作用: 我有一个包含以下内容的input.txt文件: <a> TEXT </a> <c> text asdrtlj </c> <a> another text </a> 我想在每个之前添加新行,所以我尝试了以下方法: powershell -Command "(gc input.txt) -

我对脚本非常陌生。我正在尝试解决一个问题,我正在研究windows批处理和powershell。我发现了这个,但我不知道为什么它不起作用:

我有一个包含以下内容的input.txt文件:

<a> TEXT </a>
<c> text asdrtlj </c>
<a> another text </a>
我想在每个之前添加新行,所以我尝试了以下方法:

powershell -Command "(gc input.txt) -replace '<a>', '`r`n<a>' | Out-File output.txt"
添加新行不起作用。你能帮我吗


PS:我在搜索解决方案时发现了很多复杂的代码,但我还没有理解它们,因此如果您向我推荐一些从这些语言开始的好教程,我将不胜感激

这里有几个问题。通过powershell的-command开关执行命令会由于<>字符而导致一些保留字符问题

相反,打开PowerShell.exe窗口start->run->PowerShell并直接执行命令

您还需要使用双引号而不是单引号,以便像'r和'n这样的特殊代码能够工作。此外,“n”本身也应足够:

(gc input.txt) -replace '<a>', "`n<a>" | Out-File output.txt

这里有几个问题。通过powershell的-command开关执行命令会由于<>字符而导致一些保留字符问题

相反,打开PowerShell.exe窗口start->run->PowerShell并直接执行命令

您还需要使用双引号而不是单引号,以便像'r和'n这样的特殊代码能够工作。此外,“n”本身也应足够:

(gc input.txt) -replace '<a>', "`n<a>" | Out-File output.txt

我们需要更多的引号

powershell.exe -command "(gc 1_105.jpg) -replace '<a>', """"`r`n<a>""""|Out-File output.txt"
或者如何进行一次小的重构

powershell.exe -Command "gc input.txt|%{$_.replace('<a>',[environment]::newline+'<a>')}|Out-File output.txt"

我们需要更多的引号

powershell.exe -command "(gc 1_105.jpg) -replace '<a>', """"`r`n<a>""""|Out-File output.txt"
或者如何进行一次小的重构

powershell.exe -Command "gc input.txt|%{$_.replace('<a>',[environment]::newline+'<a>')}|Out-File output.txt"

有助于解释单引号和双引号以及如何转义它们。由于<>字符而导致一些保留字符问题。这是什么意思?我在这里看到的唯一问题是单引号和一般情况下的引号?powershell-Command gc input.txt-replace,rn | Out File output.txt导致“此解决方案有效”。但我只想运行run.cmd文件。我使用类型*.xml | findstr。。。我正在尝试使用powershell,这是我的输入文件。我无法从strat->run->powerrshell运行它。因此,我正在与单引号和双引号作斗争,并摆脱它们。我会读詹姆斯C.的文章,希望能有所帮助。有助于解释单引号和双引号以及如何转义它们。由于<>字符而导致一些保留字符问题。这是什么意思?我在这里看到的唯一问题是单引号和一般情况下的引号?powershell-Command gc input.txt-replace,rn | Out File output.txt导致“此解决方案有效”。但我只想运行run.cmd文件。我使用类型*.xml | findstr。。。我正在尝试使用powershell,这是我的输入文件。我无法从strat->run->powerrshell运行它。因此,我正在与单引号和双引号作斗争,并摆脱它们。我将阅读James C.的文章,希望能有所帮助。对于学习PowerShell,我推荐这本书。对于学习PowerShell,我推荐这本书。更多引用的解决方案很好,谢谢。如果我想在一个步骤中替换更多的字符串呢。类似于这样的内容:powershell-Command Get Content input | Foreach Object{$\uuu-replace,`-replace,}| Out File output1.txt我需要转义`但不知道如何转义。:/你用反报价做什么?尝试用一对括号替换它:powershell.exe-c gc 1_105.jpg |%{$|-replace,-replace,}| sc out.txt。或者只调用[regex]的replace方法一次:powershell.exe-c gc 1_105.jpg |%{[regex]::replace$|,,{param$g@{==}[$g.value]}}}}sc out.txt。带有更多引用的解决方案很好,谢谢。如果我想在一个步骤中替换更多的字符串呢。类似于这样的内容:powershell-Command Get Content input | Foreach Object{$\uuu-replace,`-replace,}| Out File output1.txt我需要转义`但不知道如何转义。:/你用反报价做什么?尝试用一对括号替换它:powershell.exe-c gc 1_105.jpg |%{$|-replace,-replace,}| sc out.txt。或者通过调用[regex]:powershell.exe-c gc 1_105.jpg |%{[regex]::replace$|,,{param$g@{=;=}[$g.value]}}}}sc out.txt的replace方法来实现。