我有一个sample.txt 文件
Processing...
Cl.Cog="/u/l/Cg.txt"
V.DM=Nv
AL.Ft="He Se Fe",Bt,@L(Ey,0),&Ct:&Cu3
我需要将此文件分成 4 个不同的列,并在之前添加新列
输出.csv
PHP> This is hard coded line;
column1 column2 column3 column4
+-------------------+-------------------+-------------------+-------------------
abcdefg Cl Cog "/u/l/Cg.txt"
abcdefg V DM Nv
abcdefg AL Ft "He Se Fe",Bt,@L(Ey,0),&Ct:&Cu3
所以我已经尝试过了,这似乎不起作用
Get-Content test.txt |
$headerString = "PHP> This is hard coded line;"
$headerElements = $headerString -split "\s+" | Where-Object{$_}
$headerIndexes = $headerElements | ForEach-Object{$headerString.IndexOf($_)}
$results = $data
Foreach {"$(($_ -split '\s+',4)[0..2])"} |
Out-file -filepath "D:\output.txt"
我鼓励您不要尝试自己“构建”csv。专注于创建您想要的对象,然后简单地导出到 csv。您的标题行比您的数据列更多,而且您没有具体说明您想要排除processing...
行,您也没有在示例代码中考虑它,但您想要的输出没有显示它。以下是我将如何处理我相信你所追求的事情。
# Create the headers for the csv from your hard coded line
$headerString = "PHP> This is hard coded line;"
$headers = -split $headerString
# Get the text content, you can skip 1 here if you need to exclude processing
$data = Get-Content test.txt
# Iterate over each line replacing literal period and equals with a pipe.
# Combine this with your static first column value and a pipe
# I chose pipe as a delimiter as your text file had commas but not a pipe
$results = foreach($line in $data){
# again, this will create a pipe delimited string
$csv = 'abcdefg|' + ($line -replace '\.|=','|')
# convert this string to csv with your custom headers
$csv | ConvertFrom-Csv -Delimiter '|' -Header $headers
}
所有输出都收集在$results
。您现在可以查看和/或导出
$results | Format-Table
PHP> This is hard coded line;
---- ---- -- ---- ----- -----
abcdefg Cl Cog /u/l/Cg|txt
abcdefg V DM Nv
abcdefg AL Ft He Se Fe,Bt,@L(Ey,0),&Ct:&Cu3
# output to csv
$results | Export-Csv Some.csv -NoType
如果你想将表视图输出到文本文件(我不推荐它,csv更容易稍后再次使用)你可以这样做
$results | Format-Table | Out-String | Set-Content c:\temp\textfile.txt
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)