【问题标题】:Powershell ,Read from a txt file and Format Data( remove lines, remove blank spaces in between)Powershell ,从 txt 文件中读取并格式化数据(删除行,删除中间的空格)
【发布时间】:2010-06-23 18:11:47
【问题描述】:

我对 powershell 真的很陌生。我想用powershell读取一个txt文件,改成另一种格式。

  1. 从 txt 文件中读取。
  2. 格式化数据(删除行,删除中间的空格)
  3. 记录数(“T 000000002”9 个字符)

然后将输出写入新文件。

我两天前刚开始使用powershell,所以我还不知道该怎么做。

【问题讨论】:

    标签: powershell


    【解决方案1】:
    1. 从文件中读取:

      Get-Content file.txt
      
    2. 不太清楚你想要什么。 Get-Content 返回一个字符串数组。然后,您可以操纵获得的信息并将其传递。这里最有用的 cmdlet 可能是Where-Object(用于过滤)和ForEach-Object(用于操作)。

      例如,要删除所有空白行,您可以这样做

      Get-Content file.txt | Where-Object { $_ -ne '' } > file2.txt
      

      这可以缩短为

      Get-Content file.txt | Where-Object { $_ } > file2.txt
      

      因为布尔上下文中的空字符串的计算结果为false

      或者删除每一行中的空格:

      Get-Content file.txt | ForEach-Object-Object { $_ -replace ' ' } > file2.txt
      
    3. 再一次,不太清楚你在这里追求什么。从你过于详尽的描述中我能想到的可能是

      $_.Substring(2).Length
      

      $_ -match '(\d+)' | Out-Null
      $Matches[1].Length
      

    【讨论】:

    • 请注意:通过> 重定向会创建Unicode 文件。如需指定编码,请使用...| Set-Content filename -encoding Utf8
    • ... 或 Out-File,类似地。 @stej:在这种情况下,您的“Unicode”表示“UTF16-LE”:-)
    • 您好,您的帮助非常有用。但我仍在试图弄清楚如何计算行数。我可以删除空格到目前为止我的代码是 $s = get-content D:\MyScripts\members.txt | Foreach-Object { ($_ -replace '-', '') } | Foreach-Object { ($_ -replace 'OP_ID', '') } | Foreach-Object { ($_ -replace 'EFF_DT', '') } | Where-Object { $_ -ne '' }|删除空格 $s |设置内容 D:/MyScripts/nmembers.txt
    • @mahmgp:将结果存储在一个变量中,该变量将是一个Object[]。它有一个Length 属性。然后,您可以继续将其保存到文件中。或者您使用Tee-Object 将其发送到文件并在管道末尾附加Measure-Object。结果对象有一个Count 属性。
    • 谢谢罗塞尔,你的建议真的很有帮助。但是 Measure 对我不起作用。如果我使用 Measure,它会在输出中返回命名空间。因此我使用了 Count-Object $b "T {0:D9}" -f $b 下面是我的完整脚本。
    【解决方案2】:
    function Count-Object() {
        begin {
            $count = 0
        }
        process {
            $count += 1
        }
        end {
            $count
        }
    }
    
    $a= get-content .\members.txt |  
    Foreach-Object { ($_  -replace '\s','') } |
    Foreach-Object { ($_ -replace '-','') } |
    Foreach-Object { ($_ -replace 'OP_ID','') } | 
    Foreach-Object { ($_ -replace 'EFF_DT','') } |
    Where-Object { $_ -ne '' }|
    set-content  .\newmembers.txt
    
     $b = Get-Content  .\newmembers.txt |
    Count-Object $b 
     "T {0:D9}" -f $b | add-content  .\newmembers.txt
    

    【讨论】:

      【解决方案3】:

      我也喜欢?用来代替 where-object 来进一步修剪它。

      Get-Content file.txt | ?{ $_ } > file2.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-17
        相关资源
        最近更新 更多