【问题标题】:Copy table from .txt file to a new .txt file by skipping certain lines通过跳过某些行将表从 .txt 文件复制到新的 .txt 文件
【发布时间】:2019-01-22 12:26:06
【问题描述】:

我有一个这样的表格(.txt 文件):

Table:          HHBB
Displayed Fields:  1 of  5    Fixed Columns:         4     
-----------------------------------------------------------------------------
| |ID   |NAME       |Zähler |Obj       |ID-RON      |MANI   |Felder    |Nim      
|----------------------------------------------------------------------------
| |007  |Kano       |000001 |Lad       |19283712    |       |/HA       |          
| |007  |Bani       |000002 |Bad       |917391823   |       |/LA       |          

我想将此表保存到另一个 .txt 文件中,但只想跳过匹配 TableDisplayed Fields 的行。我尝试了什么:

If ([string]::IsNullOrWhitespace($tempInputRecord2) -or $_ -match "=|Table:|Displayed|----") {
     continue
}

我该怎么做?

还有一个问题: 将行逐行写入新文本文件的最佳方法是什么?

【问题讨论】:

    标签: powershell text-files line tabular skip


    【解决方案1】:

    所以您只想删除以Table:Displayed Fields: 开头的行并将结果输出到新文件?使用Where-Object 过滤行,使用Out-File 将它们写入文件:

    Get-Content test.txt |
    Where-Object { $_ -notlike "Table:*" -and $_ -notlike "Displayed Fields:*" } |
    Out-File test2.txt
    

    【讨论】:

    • 好极了! . Dankeschön,帽子超级棒!
    【解决方案2】:

    简单的任务有很多方法:

    1. 如果要跳过的标头只出现一次:
    Get-Content test.txt|Select-Object -Skip 2|Set-Content test2.txt
    1. -notmatch 和 RegEx 交替的类似方法
    Get-Content test.txt|Where-Object {$_ -notmatch '^Table:|^Displayed Fields:'}|Set-Content test2.txt
    1. 通过用括号括起来强制完全读入内存时,您可以写入同一个文件:
    (Get-Content test.txt)|Select-Object -Skip 2|Set-Content test.txt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 2019-03-20
      相关资源
      最近更新 更多