【问题标题】:Powershell Cut Character Position StringPowershell 剪切字符位置字符串
【发布时间】:2015-08-04 14:53:21
【问题描述】:

您好,我如何将此 BASH 脚本复制到 powershell 中?它采用一个基本字符串并抓取这些特定块并在其间放置一个管道并将其写入 csv 文件。我知道如何获取内容和输出到 csv,但是在 powershell 中切碎字符串的最佳方法是什么?

`cat /app/$filename |cut  -c1-9,19-138,139-198,199-238,239-240,241-245,287-296 --output-delimiter="|" >> /app/CSVs/$filename.csv`

我以前使用过 split() ,但它似乎不是正确的方法。我正在考虑循环遍历每一行并保存该行的每一段并保存到一个新的字符串 var 并为每个部分添加分隔符。这似乎非常低效。

想法?

源文件由字符位置构成,有很多空格。每个字段都有一定数量的字符空间。 (它基本上是一个数据库文件,但非常简单的 txt 格式)

1-9 = ID (9 chars long)
19-138 = business_name (120 chars long)
139-198 = address (60 chars long)
198-237 = city (40 chars long)
238-239 = state (2 chars long)
240-244 = zip_code (5 chars long)
286-295 = phone (10 chars long)

我认为使用 $string.substring(char#,length) 将与循环一起使用,但帮助越多越好。

输出应该是这样的

123456789|acme business <lots of spaces>|1234 main st <lots of spaces>|etc...

【问题讨论】:

  • 您能提供源文件和生成的 CSV 示例吗?源文件是结构化的(有某种分隔符吗?)还是你只是从预定位置抓取块?
  • 在帖子中添加了信息。是的,你的最后一个问题。我只是从预定位置抓取块。

标签: string bash powershell csv cut


【解决方案1】:

看起来像是新 PS 5 cmdlet ConvertFrom-String 的工作:

很遗憾,我还没有尝试过,所以我无法提供示例。但也可以使用正则表达式来完成:

Get-Content -Path '.\db.txt' |
    ForEach-Object{$_ -replace '^(.{9})(.{120})(.{60})(.{40})(.{2})(.{5})(.{10})$', '$1|$2|$3|$4|$5|$6|$7'} |
        Set-Content -Path '.\db.csv'

Get-Content\Set-Contentquite slow,因此为了加快处理速度,您可以切换到 StreamReader\StreamWriter。请参阅我对这个问题的回答:More-efficient way to modify a CSV file's content,我在脚本中使用它们来加快速度。

【讨论】:

    【解决方案2】:
    $subChar =0,18,138,198,238,240,286 
    $subLength =9,120,60,40,2,5,10 
    
    $file = Get-content 'C:\Users\jwannemacher\Desktop\out.txt'
    Foreach($line in $file)
    {
        $lineCounter
        $array = @()
        $lineLoop = 0
        $charLoop = 0
    
        foreach($sub in $subChar)
        {
            $word = $line.Substring($subChar[$charLoop],$subLength[$charLoop])
            $array += $word
            $charLoop++
        }
    $array -join '|' | Out-File C:\file1.csv -Append
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2022-01-21
      • 2021-01-08
      • 2013-01-14
      • 2019-02-01
      相关资源
      最近更新 更多