如何将 sed 命令转换为其等效的 PowerShell 命令?

How can i convert a sed command to its PowerShell equivalent?

编者注:


我有一个 mac 命令,我需要它在 windows 上 运行。我对 mac 没有任何经验。

sed -i '' 's/././g' dist/index.html

经过研究我发现我应该使用

get-content path | %{$_ -replace 'expression','replace'}

但还不能让它工作。

:

  • 假设您的 sed 命令中的 s/././g 只是一个 示例 字符串替换 已选择作为 real-world 个的占位符。此示例替换所做的是用 verbatim . 替换换行符(正则表达式 .)以外的所有字符,因此,执行 不要 运行 在你的文件上使用 as-is 下面的命令,除非你准备好让他们的角色变成 .

直接翻译您的 sed 命令,它执行 in-place 输入文件的更新,是(ForEach-Object 是 built-in % 别名所指的 cmdlet 的名称):

(Get-Content dist/index.html) | 
  ForEach-Object { $_ -replace '.', '.' } |
    Set-Content dist/index.html -WhatIf

注意:上面命令中的-WhatIf common parameter预览操作。一旦您确定该操作将执行您想要的操作,请删除 -WhatIf

或者,更有效:

(Get-Content -ReadCount 0 dist/index.html) -replace '.', '.' | Set-Content dist/index.html -WhatIf

-ReadCount 0 在输出结果之前将行读入 单个数组 ,而不是发出每一行的默认行为 一个接一个到管道

或者,如果不需要 line-by-line 处理并且 -replace 操作可以应用到 整个文件内容,使用-Raw开关:

(Get-Content -Raw dist/index.html) -replace '.', '.' | Set-Content -NoNewLine dist/index.html -WhatIf

注:

  • -replaceregular-expression-based string replacement operator 使用语法 <input> -replace <regex>, <replacement> 并且 总是 执行全局替换(根据g 选项在你的 sed 命令中),即替换 all 它找到的匹配项。

    • 然而,与 sed 的正则表达式不同,PowerShell 的正则表达式默认是 不区分大小写的 ;要使它们区分大小写 ,请使用 -creplace 运算符变体。
  • 请注意同一管道中 Get-Content call, which ensures that the file is read into memory in full and closed again first, which is the prerequisite for being able to rewrite the file with Set-Content 周围所需的 (...)

    • 警告:虽然不太可能,但这种方法可能会导致数据丢失,即如果保存回输入文件的写入操作被中断。
  • 您可能需要 -EncodingSet-Content 以确保重写的文件使用与原始内容相同的字符编码 - Get-Content 将文本文件读入 . NET 字符串识别各种编码,并且不保留关于遇到什么编码的信息。

  • 除了 Get-Content -Raw / Set-Content -NoNewLine 解决方案保留原始换行符格式外,输出文件将使用 platform-native 换行格式 - Windows 上的 CRLF (\r\n),Unix-like 平台上的 LF (\n) - 无论输入文件最初使用哪种格式。