gpt4 book ai didi

Powershell 文本处理 : Join specific lines of a txt file

转载 作者:行者123 更新时间:2023-12-04 07:40:02 26 4
gpt4 key购买 nike

我必须处理一些文本并遇到一些困难:
文本 .\text.txt 的格式如下:

name,
surname,
address,

name.
surname,
address,
等等。
我想要实现的是加入以“,”结尾的对象,如下所示:
name,surname,address

name,surname,address
等等
我正在做这样的事情:
$content= path to the text.txt
$result= path to the result file

Get-Content -Encoding UTF8 $content | ForEach-object {
if ( $_ -match "," ) {
....join the selected lines....
}
} |Set-Content -Encoding UTF8 $result
我还需要考虑的是,以“,”结尾的行可能有一个空行,它应该是 $result 中的 CR。

最佳答案

您可以通过首先拆分空换行符上的数据块来做到这一点:

# read the content of the file as one single multiline string
$content = Get-Content -Path 'Path\To\The\file.txt' -Raw -Encoding UTF8
# split on two or more newlines and dispose of empty blocks
$content -split '(\r?\n){2,}' | Where-Object { $_ -match '\S' } | ForEach-Object {
# trim the text block, split on newline and remove the trailing commas (or dots)
# output these joined with a comma
($_.Trim() -split '\r?\n' ).TrimEnd(",.") -join ','
} | Set-Content -Path 'Path\To\The\NEW_file.txt' -Encoding UTF8
输出:
name,surname,address
name,surname,address

关于Powershell 文本处理 : Join specific lines of a txt file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67532267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com