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

M--*_*M-- 1 powershell text-processing cygwin cmd

我想更换两个字符串之间的线条[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!!!
Run Code Online (Sandbox Code Playgroud)

sed:

sed -e '/[REPORT]/,/[TAGS]/c\[REPORT]\nmy text goes here\nAnd a new line down here\n[TAGS]' minput.txt > moutput.txt
Run Code Online (Sandbox Code Playgroud)

这给了我这个:

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!!!
Run Code Online (Sandbox Code Playgroud)

当我这样做并在记事本中打开输出文件时,它不会显示新行.我认为这是因为格式化问题,简单Dos2Unix应该解决问题.

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

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

小智 5

使用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"
Run Code Online (Sandbox Code Playgroud)

-replace正则表达式使用nonconsuming 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!!!
Run Code Online (Sandbox Code Playgroud)

要从文件中读取文本,替换并回写(即使不存储在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"
Run Code Online (Sandbox Code Playgroud)

括号必须在一个管道中重用相同的文件名.