将文本文件中的多行组合/合并为一行 (Powershell)

2024-05-07

我有一个文本文件,其中包含如下内容:

blah, blah, blah ...

Text : {string1, string2, string3,
        string4, string5, string6,}

blah, blah, blah ...

Text : {string7, string8, string9,
        string10, string11, string12,}

我只想将大括号之间的线合并为一行,如下所示:

blah, blah, blah ...

Text : {string1, string2, string3, string4, string5, string6,}

blah, blah, blah ...

Text : {string7, string8, string9, string10, string11, string12,}

但是,我不想将更改应用于整个文本文件,因为它包含其他内容。我只想编辑大括号 { ... } 之间的文本。我搞砸了-join但无法让它发挥作用。我有以下脚本,用于打开文件、进行更改并输出到另一个文件中:

gc input.txt | 

# Here I have several editing commands, like find/replace.
# It would be great if I could add the new change here.

sc output.txt

谢谢你!


尝试这个:

$text = (Get-Content .\input.txt) -join "`r`n"
($text | Select-String '(?s)(?<=Text : \{)(.+?)(?=\})' -AllMatches).Matches | % {
        $text = $text.Replace($_.Value, ($_.Value -split "`r`n" | % { $_.Trim() }) -join " ")
}
$text | Set-Content output.txt

它修剪掉每行开头和结尾的多余空格,并用空格连接所有行。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将文本文件中的多行组合/合并为一行 (Powershell) 的相关文章

随机推荐