如何在文件中组合多组行? [英] How can I combine multiple groups of lines in a file?

查看:26
本文介绍了如何在文件中组合多组行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文件中的几组行组合成 CSV 行(这些组之间由一个空行分隔).我刚刚为这个例子复制了几次行,但实际数据文件中每个组的信息会有所不同.

I am trying to combine several groups of lines in a file into CSV lines (the groups being separated by one blank line in between each other). I've just copied the lines several times for this example but the information would differ for each group in the actual data files.

IM123456
01/20/16 09:44:01 
Reassignment 
PZSR7Z 
Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 


IM123456
01/20/16 09:44:01 
Reassignment 
PZSR7Z 
Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 


IM123456
01/20/16 09:44:01 
Reassignment 
PZSR7Z 
Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 


IM123456
01/20/16 09:44:01 
Reassignment 
PZSR7Z 
Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 

IM123456
01/20/16 09:44:01 
Reassignment 
PZSR7Z 
Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 

使用上面粘贴的输出,我怎样才能让它像下面这样?

With the output pasted above, how could I get it to resemble the following?

IM123456,01/20/16 09:44:01,Reassignment,PZSR7Z,Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 
IM123456,01/20/16 09:44:01,Reassignment,PZSR7Z,Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 
IM123456,01/20/16 09:44:01,Reassignment,PZSR7Z,Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 
IM123456,01/20/16 09:44:01,Reassignment,PZSR7Z,Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 
IM123456,01/20/16 09:44:01,Reassignment,PZSR7Z,Reassignment from xxx-xxx-xxx-xxx to xxx-xxx-xxx-xxx-xxx-xxx-xxx 

我尝试使用 此处,但我很难将其应用到我的示例中.

I attempted to utilize the solution from here, but I had a difficult time applying it to my example.

推荐答案

将文件作为一个整体读取,将其拆分为 2 个或更多连续换行符,删除空元素,然后用逗号替换剩余的换行符并将所有内容写回到一个文件.

Read the file as a whole, split it at 2 or more consecutive line breaks, remove empty elements, then replace the remaining line breaks with commas and write everything back to a file.

(Get-Content 'C:\path\to\input.txt' -Raw) -split ' *(\r\n){2,}' |
  Where-Object { $_.Trim() } |
  ForEach-Object { $_ -replace ' *\r\n', ',' } |
  Set-Content 'C:\path\to\output.csv'

如果您的 PowerShell 版本不支持 Get-Content -Raw 通过 Out-String 管道传输 Get-Content 输出:

If your PowerShell version doesn't support Get-Content -Raw pipe the Get-Content output through Out-String:

(Get-Content 'C:\path\to\input.txt' | Out-String) ...

这篇关于如何在文件中组合多组行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆