【问题标题】:Combine/Merge Multiple Lines into One Line from a Text File (Powershell)将文本文件中的多行合并/合并为一行(Powershell)
【发布时间】:2013-02-14 20:55:30
【问题描述】:

我有一个包含以下内容的文本文件:

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

谢谢!

【问题讨论】:

    标签: powershell


    【解决方案1】:

    试试这个:

    $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
    

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

    【讨论】:

    • 这适用于整个文本文件。如果可能的话,我只想将它应用于大括号之间的文本。
    • 查看更新的答案。这与您现在也回答的其他问题几乎相同。
    • 这是一种不同的方法,所以我认为值得提出一个新问题。您的解决方案适用于第一组'Text : {'。但随后它也会更改(修剪和连接)它之后的所有内容。因此,它不仅限于整个文件中大括号之间的文本。我编辑了这个问题,以便更好地表示文件中的内容。非常感谢您的帮助 Graimer。
    【解决方案2】:

    罐装大虾:

    $testdata = @'
    blah, blah, blah ...
    
    Text : {string1, string2, string3,
            string4, string5, string6,}
    
    blah, blah, blah ...
    
    Text : {string7, string8, string9,
            string10, string11, string12,}
    '@
    
    $testfile = 'c:\testfiles\testfile.txt'
    $testdata | sc $testfile
    $text = [IO.File]::ReadAllText($testfile)
    
    $regex = @'
    (?ms)(Text\s*:\s\{[^}]+)\s*
    \s*([^}]+)\s*
    '@
    
    $text -replace $regex,'$1 $2'
    

    呸呸呸呸……

    文本:{string1, string2, string3, string4, string5, string6,}

    呸呸呸呸……

    文本:{string7, string8, string9, string10, string11, string12,}

    【讨论】:

    • 不错的解决方案,但这仅支持 2 行。它应该是动态的。
    • 除非我误读了这个问题,否则这就是目标。它将匹配并替换文本中任何位置的这两行。我会更新答案以更具示范性。
    • 他的文件实际上是这样的:stackoverflow.com/questions/14840632/…,它有 3 行。它是一个日志文件什么的,所以我猜“文本”部分可以是 1 行,10 行,不时变化
    • 它将匹配此处字符串中的任何内容(即“can”),而巨型虾选项 (?ms) 意味着您可以编写它以匹配多行。 A .+ 将匹配多行。将正则表达式段放在此处字符串中的单独行上是隐式地将 ^ 和 $ 锚点添加到正则表达式的那部分。
    猜你喜欢
    • 2015-10-23
    • 2019-06-25
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多