使用 PowerShell 从文本文件中提取列 [英] Extracting columns from text file using PowerShell

查看:109
本文介绍了使用 PowerShell 从文本文件中提取列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从本文中解释的文本文件中提取列:

I have to extract columns from a text file explained in this post:

使用 Perl 从文本文件中提取列one-liner:类似于Unix cut

但我也必须在未安装 Perl 的 Windows Server 2008 中执行此操作.我怎么能用 PowerShell 做到这一点?任何想法或资源?我是 PowerShell 菜鸟...

but I have to do this also in a Windows Server 2008 which does not have Perl installed. How could I do this using PowerShell? Any ideas or resources? I'm PowerShell noob...

推荐答案

试试这个:

Get-Content test.txt | Foreach {($_ -split '\s+',4)[0..2]}

如果您希望将这些列中的数据打印在同一行上:

And if you want the data in those columns printed on the same line:

Get-Content test.txt | Foreach {"$(($_ -split '\s+',4)[0..2])"}

请注意,对于 -split 运算符,这需要 PowerShell 2.0.此外,,4 告诉拆分运算符您想要的最大拆分字符串数,但请记住,最后一个字符串将始终包含所有附加字符串.

Note that this requires PowerShell 2.0 for the -split operator. Also, the ,4 tells the the split operator the maximum number of split strings you want but keep in mind the last string will always contain all extras concat'd.

对于固定宽度的列,这里是列宽等于 7 ($w=7) 的一种方法:

For fixed width columns, here's one approach for column width equal to 7 ($w=7):

$res = Get-Content test.txt | Foreach {
           $i=0;$w=7;$c=0; `
           while($i+$w -lt $_.length -and $c++ -lt 2) {
               $_.Substring($i,$w);$i=$i+$w-1}}

$res 将包含所有行的每一列.要设置最大列数,请将 $c++ -lt 2 从 2 更改为其他内容.可能有一个更优雅的解决方案,但现在没有时间考虑它.:-)

$res will contain each column for all rows. To set the max columns change $c++ -lt 2 from 2 to something else. There is probably a more elegant solution but don't have time right now to ponder it. :-)

这篇关于使用 PowerShell 从文本文件中提取列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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