Powershell文本处理:连接txt文件的特定行
我不得不处理一些文本,遇到了一些困难: 文本。\text.txt的格式如下:Powershell文本处理:连接txt文件的特定行,powershell,text,script,Powershell,Text,Script,我不得不处理一些文本,遇到了一些困难: 文本。\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 UT
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
等
我在做这样的事情:
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
我需要考虑的是,以“,”结尾的行可能有下一行空,这应该是一个CR在<代码> $结果< /代码>
所有的术语以<代码>结束,< /代码>,因此您可以使用正则表达式:$content= "C:\test.txt"
$result= "path to the result file"
$CR = "`r`n"
$lines = Get-Content -Encoding UTF8 $content -raw
$option = [System.Text.RegularExpressions.RegexOptions]::Singleline
$lines = [regex]::new(',(?:\r?\n){2,}', $option).Replace($lines, $CR + $CR)
$lines = [regex]::new(',\r?\n', $option).Replace($lines, ",")
$lines | Out-File -FilePath $result -Encoding utf8
结果:
name,surname,address
name1,surname,address
name,surname,address
name,surname,address
下面的代码将给出所需的结果
$content= "Your file path"
$resultPath = "result file path"
Get-Content $content | foreach {
$data = $_
if($data -eq "address,")
{
$NewData = $data -replace ',',''
$data = $NewData + "`r`n"
}
$out = $out + $data
}
$out | Out-File $resultPath
可以通过首先拆分空换行符上的数据块来完成此操作:
# 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
您给出的示例没有反映以“,”结尾的对象,因为
地址
也以逗号结尾,而在下一个块中名称
以句号结尾。我们没有收到您的消息。。给出的答案解决了你的问题吗?如果是,请点击大的复选图标“代码>✓代码>在左边。这将帮助其他有类似问题的人更容易找到它。谢谢我使用了你的方法并得到了我想要的结果。@valente很高兴帮助你,别忘了验证并投票结束问题。。