首页 > 解决方案 > 使用 Powershell 拆分文本文件

问题描述

我正在尝试使用 Powershell 将基于多个字符串的文本文件拆分为两个文件。文件大小从 5KB-15KB 不等。

文件数据格式如下:

18600 - ABCD 2204 2020-04-11 00:00:00

18600 - ABCD 2204 2020-04-11 00:00:00

18600 - ABCD 2204 2020-04-11 00:00:00

18113 - ABCD 2204 2020-04-11 00:00:00

18113 - ABCD 2204 2020-04-11 00:00:00

19873 - ABCD 2204 2020-04-11 00:00:00

18764 - ABCD 2204 2020-04-11 00:00:00

19000 - ABCD 2204 2020-04-11 00:00:00

我需要将所有以 18600、18113、19000 等(或任何一组指定的 5 位数字)开头的行拆分到一个文件中,并将所有剩余的不以这些数字(其他)开头的数据行拆分到第二个文件中。

所以逻辑是,对于文件中的每一行,如果它以这些指定的数字集开头,则写入“file1”,否则将其写入“file2”。

$file = (Get-Content myfile.txt)
ForEach ($line in $file) {
  If ($line -match a set of strings) 
{
$newfile = all lines with set of beginning strings
}
Else {
$line | Out-File -Append different file
}    
}

我也愿意接受 powershell 之外的任何其他建议。非常感谢你的帮助。

标签: powershell

解决方案


假设您想要所有以 18000..18999 范围内的数字开头的行,这可以完成工作... []

它能做什么 ...

  • 设置常量
  • 创建一个文件以
    在准备好对您的数据执行此操作时使用,将整个#region/#endregion块替换为对Get-Content.
  • 加载输入文件
  • 遍历该集合
  • 拆分当前行以获取第一个空格之前的部分
  • 将其转换为[int]
  • 检查它是否在所需的范围内
  • 如果是,将其发送到18文件
  • 如果否,将其发送到非 18 文件

这段代码...

  • 缺乏任何重大的错误处理
  • 不跟踪所做的事情
  • 不显示发生了什么

编码 ...

$SourceDir = "$env:TEMP\WBCha"
$TargetNumberRange = 18000..18999
$InFile = Join-Path -Path $SourceDir -ChildPath 'InFile.txt'
$18OutFile = Join-Path -Path $SourceDir -ChildPath '18_OutFile.txt'
$Not_18OutFile = Join-Path -Path $SourceDir -ChildPath 'Not_18OutFile.txt'

#region >>> create a file to work with
#    when ready to do this for real, replace the whole "region" block with a Get-Contnet call
if (-not (Test-Path -LiteralPath $SourceDir))
    {
    $Null = New-Item -Path $SourceDir -ItemType 'Directory' -ErrorAction 'SilentlyContinue'
    }
$HowManyLines = 1e1
$Content = foreach ($Line in 0..$HowManyLines)
    {
    $Prefix = @(18,19)[(Get-Random -InputObject @(0, 1))]
    '{0}{1:d3} - {2}' -f $Prefix, $Line, [datetime]::Now.ToString('yyyyy-MM-dd HH:mm:ss:ffff')
    }
$Content |
    Set-Content -LiteralPath $InFile -ErrorAction 'SilentlyContinue'
#endregion >>> create a file to work with


foreach ($IF_Item in (Get-Content -LiteralPath $InFile))
    {
    if ([int]$IF_Item.Split(' ')[0] -in $TargetNumberRange)
        {
        Add-Content -LiteralPath $18OutFile -Value $IF_Item
        }
        else
        {
        Add-Content -LiteralPath $Not_18OutFile -Value $IF_Item
        }
    }

文件18内容...

18000 - 02020-07-10 12:29:45:6736
18001 - 02020-07-10 12:29:45:6736
18004 - 02020-07-10 12:29:45:6746
18005 - 02020-07-10 12:29:45:6756
18006 - 02020-07-10 12:29:45:6756
18008 - 02020-07-10 12:29:45:6766
18010 - 02020-07-10 12:29:45:6766

文件not 18内容...

19002 - 02020-07-10 12:29:45:6746
19003 - 02020-07-10 12:29:45:6746
19007 - 02020-07-10 12:29:45:6756
19009 - 02020-07-10 12:29:45:6766

推荐阅读