希望使用 powershell 从文本文件中删除文本

Joh*_*ens 2 powershell command-line replace

我正在尝试编辑一个包含各种 html 元素的大型纯文本文档,如下所示:

  • <p> & </p>
  • <script> & </script>
  • <style> & </style>
  • <div> & </div>
  • 在更极端的情况下;<span style="color: #ff0000;"> & </span>

<UniqueText>我的目标是从文本文件中删除任何内容。我没有太多使用 powershell,所以我的知识有限,但我还是尝试了一下。

用于更换全部<UniqueText>

get-content "C:\Users\John\Desktop\input.txt" | -replace "\<.*?\>","" | Out-File C:\Users\John\Desktop\output.txt
Run Code Online (Sandbox Code Playgroud)

上面的脚本给出了以下错误:

-replace :术语“-replace”不被识别为 cmdlet、函数、脚本文件或可操作程序的名称。

Pax*_*axz 5

使用时-replace必须确保正确解析调用的字符串。有两种方法可以解决您的问题:

1.使用 foreach 遍历文件的每一行并-replace在每一行上使用(如果您想对这些行执行其他操作,这可能会有所帮助):

get-content "C:\Users\John\Desktop\input.txt" | % {$_ -replace "\<.*?\>",""} | Out-File C:\Users\John\Desktop\output.txt
Run Code Online (Sandbox Code Playgroud)

%是别名foreach

$_是 的元素foreach,因此文件的每一行

2.对文件使用替换而不遍历每一行:

(get-content "C:\Users\John\Desktop\input.txt") -replace "\<.*?\>","" |  Out-File C:\Users\John\Desktop\output.txt
Run Code Online (Sandbox Code Playgroud)