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

标签 powershell replace command-line

我正在尝试编辑包含各种 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

上面的脚本报错如下:

-replace : The term '-replace' is not recognized as the name of a cmdlet, function, script file, or operable program.

最佳答案

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

1. 使用 foreach 遍历文件的每一行并在每一行上使用 -replace(如果您想对行):

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

%foreach

的别名

$_foreach 的元素,所以文件的每一行

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

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

关于powershell - 希望使用 powershell 从文本文件中删除文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51898335/

相关文章:

python - 如何根据Python中的字典替换大字符串的子字符串?

javascript - Node : Command line utitly in Windows

maven - 即使 POM 打包指定了 WAR,我是否可以强制 Maven 构建 JAR?

powershell - Register-EventObject 在监听进程时不更新控制台

powershell - 在Powershell中使用UFormat转换时为什么会出现语法错误

java替换字符串中的字符

php - 从命令行执行时如何阻止 PHP 返回 header ?

powershell - 如何在PowerShell中调用带有输出参数的方法?

sharepoint - 在SharePoint Online中使用Powershell更改列表字段

JavaScript RegEx 取代 HTML 编码