分割包含固定长度列的字符串 [英] Split a string containing fixed length columns

查看:89
本文介绍了分割包含固定长度列的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这样的数据:

3LLO24MACT01 24MOB_6012010051700000020100510105010              123456

导入时,它为不同的列包含不同的值.

It contains different values for different columns when I import it.

每列都是固定宽度的

  • Col#1是ID,长度仅为1.表示这里是"3".
  • Col#2的长度为3,在这里为"LLO".
  • Col#3的长度为9,长度为"24MACT01 "(请注意,丢失的空白被空白填充).
  • 这种情况持续15列左右...
  • Col#1 is the ID and just 1 long. Meaning it is "3" here.
  • Col#2 is 3 in length and here "LLO".
  • Col#3 is 9 in length and "24MACT01 " (notice that the missing ones gets filled up by blanks).
  • This goes on for 15 columns or so...

是否有一种方法可以根据序列长度将其快速切成不同的元素?我找不到任何东西.

Is there a method to quickly cut it into different elements based on sequence length? I couldn't find any.

推荐答案

这可以通过RegEx匹配并创建自定义对象数组来完成.像这样:

This can be done with RegEx matching, and creating an array of custom objects. Something like this:

$AllRecords = Get-Content C:\Path\To\File.txt | Where{$_ -match "^(.)(.{3})(.{9})"} | ForEach{
    [PSCustomObject]@{
        'Col1' = $Matches[1]
        'Col2' = $Matches[2]
        'Col3' = $Matches[3]
    }
}

这将占用每一行,根据指定的字符数进行匹配,然后根据这些匹配项创建一个对象.它收集数组中的所有对象,并且可以导出到CSV或其他格式.由于缺乏更好的信息,我建议使用"Col1","Col2"等通用列标题,并且可以是您想要的任何东西.

That will take each line, match by how many characters are specified, and then create an object based off those matches. It collects all objects in an array and could be exported to CSV or whatever. The 'Col1', 'Col2' etc are just generic column headers I suggested due to a lack of better information, and could be anything you wanted.

编辑:谢谢iCodez也许无意间向我展示了您可以为代码示例指定一种语言!

Thank you iCodez for showing me, perhaps inadvertantly, that you can specify a language for your code samples!

这篇关于分割包含固定长度列的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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