我有一个包含多行的文件,每行包含5个以逗号分隔的部分。我正在尝试拆分这些行并从一行中的同一行返回多个部分。我的尝试是这样的:
Get-Content $file | ForEach-Object { $_.split(",")[0,1] }
不幸的是,它会在单独的行上返回每个元素。如果在PowerShell中有另一种工作方式,我对此持开放态度。
答案 0 :(得分:0)
此?
Get-Content $file | ForEach-Object { -join $_.split(",")[0,1] }
答案 1 :(得分:0)
如果您的输入是CSV,为什么不使用Import-Csv并创建一个对象。
[file.csv]
this,is,the,first,line
this,is,the,second,line
然后,
$csv = Import-Csv 'C:\tmp\file.csv' -Header One,Two,Three,Four,Five
这给了你:
PS> $csv | Format-Table -AutoSize
One Two Three Four Five
--- --- ----- ---- ----
this is the first line
this is the second line
现在抓住你需要的东西:
PS> $csv[0].Four + ' ' + $csv[0].Five
first line
PS> 0..$csv.Count | % {$csv[$_].Four + ' ' + $csv[$_].Five}
first line
second line