【问题标题】:PowerShell: How to remove columns from delimited text input?PowerShell:如何从分隔文本输入中删除列?
【发布时间】:2011-08-16 05:35:03
【问题描述】:

我有一个包含 5 列由空格分隔的文本的文本文件。例如:

10 45 5 23 78
89 3 56 12 56
999 4 67 93 5

使用 PowerShell,我如何删除最右边的两个 ?结果文件应该是:

10 45 5
89 3 56
999 4 67

我可以使用-split 运算符提取单个项目。但是,这些项目出现在不同的行上,我不知道如何才能将它们作为每行 3 个项目取回。

为了使问题更通用(并且对其他人有帮助):如何使用 PowerShell 删除[0,n-1] 范围内多列的数据,给定一个输入,其中每个行都有n 列的分隔数据?

【问题讨论】:

    标签: powershell split


    【解决方案1】:

    读取文件内容,将其转换为 csv 并仅选择前 3 列:

    Import-Csv .\file.txt -Header col1,col2,col3,col4,col5 -Delimiter ' ' | Select-Object col1,col2,col3
    

    如果你只想要值(没有标题):

    Import-Csv .\file.txt -Header col1,col2,col3,col4,col5 -Delimiter ' ' | Select-Object col1,col2,col3 | Format-Table -HideTableHeaders -AutoSize
    

    将结果保存回文件:

    (Import-Csv .\file.txt -Header col1,col2,col3,col4,col5 -Delimiter ' ') | Foreach-Object { "{0} {1} {2}" -f $_.col1,$_.col2,$_.col3} | Out-File .\file.txt
    

    更新:

    只是另一种选择:

    (Get-Content .\file.txt) | Foreach-Object { $_.split()[0..2] -join ' ' } | Out-File .\file.txt
    

    【讨论】:

    • 太棒了!我忘记了 PowerShell 有 CSV 命令 :-)
    【解决方案2】:

    一种方法是:

    gc input.txt | %{[string]::join(" ",$_.split()[0..2]) } | out-file output.txt
    

    (将 2 替换为 n-1)

    【讨论】:

      【解决方案3】:

      这是通用解决方案:

      param
      (
          # Input data file
          [string]$Path = 'data.txt',
          # Columns to be removed, any order, dupes are allowed
          [int[]]$Remove = (4, 3, 4, 3)
      )
      
      # sort indexes descending and remove dupes
      $Remove = $Remove | Sort-Object -Unique -Descending
      
      # read input lines
      Get-Content $Path | .{process{
          # split and add to ArrayList which allows to remove items
          $list = [Collections.ArrayList]($_ -split '\s')
      
          # remove data at the indexes (from tail to head due to descending order)
          foreach($i in $Remove) {
              $list.RemoveAt($i)
          }
      
          # join and output
          $list -join ' '
      }}
      

      【讨论】:

      • 以防万一,-split '\s+'(加上+)将被任意数量的空格分割。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 2017-11-23
      • 2019-05-15
      相关资源
      最近更新 更多