powershell - 替换两个特定字符串之间的行 - 在 cmd 中等效于 sed

标签 powershell cmd cygwin text-processing

我想替换两个字符串 [REPORT][TAGS] 之间的行。文件看起来像这样

Many lines 
many lines
they remain the same

[REPORT]

some text
some more text412

[TAGS]

text that I Want
to stay the same!!!

我在 中使用了 sed :

sed -e '/[REPORT]/,/[TAGS]/c\[REPORT]\nmy text goes here\nAnd a new line down here\n[TAGS]' minput.txt > moutput.txt

这给了我这个:

Many lines 
many lines
they remain the same

[REPORT]
my text goes here
And a new line down here
[TAGS]

text that I Want
to stay the same!!!

当我这样做并在记事本中打开输出文件时,它不显示新行。我假设这是因为格式问题,一个简单的 Dos2Unix 应该可以解决这个问题。

但正因为如此,也主要是因为并非我所有的同事都可以访问 cygwin 我想知道是否有办法在 中执行此操作(或者 Powershell 如果没有办法进行批处理)。

最后,我想在多个文件上运行它,并将它们的这一部分(在上述两个词之间)更改为我提供的文本。

最佳答案

使用从 Windows 7 开始提供的 PowerShell。

## Q:\Test\2018\10\30\SO_53073481.ps1
## defining variable with a here string
$Text = @"
Many lines 
many lines
they remain the same

[REPORT]

some text
some more text412

[TAGS]

text that I Want
to stay the same!!!
"@

$Text -Replace "(?sm)(?<=^\[REPORT\]`r?`n).*?(?=`r?`n\[TAGS\])",
               "`nmy text goes here`nAnd a new line down here`n"

-replace 正则表达式使用非消耗 lookarounds

示例输出:

Many lines
many lines
they remain the same

[REPORT]

my text goes here
And a new line down here

[TAGS]

text that I Want
to stay the same!!!

要从文件中读取文本,替换并写回(即使不存储在 var 中),您可以使用:

(Get-Content ".\file.txt" -Raw) -Replace "(?sm)(?<=^\[REPORT\]`r?`n).*?(?=`r?`n\[TAGS\])",
               "`nmy text goes here`nAnd a new line down here`n"|
Set-Content ".\file.txt"

括号是在一个管道中重用相同文件名所必需的。

关于powershell - 替换两个特定字符串之间的行 - 在 cmd 中等效于 sed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53073481/

相关文章:

xml - PowerShell-V5 Invoke-Webrequest 添加 2 个 header 授权 header 和接受 header

Powershell 别名似乎不适用于包含 - 的别名

java - Cygwin 运行的 java 版本与 windows powershell 不同

regex - 使用 Powershell 替换正则表达式结果的小节

powershell - 使用-notlike在PowerShell中过滤出多个字符串

c# - 通过命令行或 C# 创建 EF 模型

dll - 如何使用ilMerge将dll合并成一个exe文件?

file - BAT 文件执行后保持 CMD 打开

java - 如何将 Shell 脚本添加为 Java 项目的一部分

cygwin - cygpath 无法将 Windows 路径转换为 ​​Linux 路径