【问题标题】:How can I split a large tab delimited text file into separate files by date field and use the date in the file name如何按日期字段将大制表符分隔的文本文件拆分为单独的文件并在文件名中使用日期
【发布时间】:2022-08-17 01:45:12
【问题描述】:

我有一个非常大的文本文件 400K+ 行。我需要将它分成多个文件。我目前将它与第 3 ([2]) 列分开并将文本文件设置为该名称,但这些文件仍然太大。如果可能的话,我想按名称和月份分开。

文件如下所示:

7/1/2022 9:00   7/1/2022 10:00  25823-0001
7/1/2022 10:00  7/1/2022 11:00  25823-0001 ...
7/1/2022 11:00  7/1/2022 12:00  25823-0001 ...
7/1/2022 12:00  7/1/2022 13:00  25823-0001 ...
7/2/2022 13:00  7/2/2022 14:00  25823-0001 ...
7/2/2022 14:00  7/2/2022 15:00  25823-0001 ...
7/2/2022 15:00  7/2/2022 16:00  25823-0001 ...
7/2/2022 16:00  7/2/2022 17:00  25823-0001 ...
7/2/2022 17:00  7/2/2022 18:00  25823-0001 ...
8/1/2022 18:00  8/1/2022 19:00  25823-0001 ...
8/1/2022 19:00  8/1/2022 20:00  25823-0001 ...
8/1/2022 20:00  8/1/2022 21:00  25823-0001 ...
8/1/2022 21:00  8/1/2022 22:00  25823-0001 ...
8/1/2022 22:00  8/1/2022 23:00  25823-0001 ...
8/1/2022 23:00  8/2/2022 0:00   25823-0001 ...
8/2/2022 0:00   8/2/2022 1:00   25823-0001 ...
8/2/2022 1:00   8/2/2022 2:00   25823-0001 ...

所以文件最终会是 25823-0001_202207.txt 并包含

7/1/2022 9:00   7/1/2022 10:00  25823-0001
7/1/2022 10:00  7/1/2022 11:00  25823-0001 ...
7/1/2022 11:00  7/1/2022 12:00  25823-0001 ...
7/1/2022 12:00  7/1/2022 13:00  25823-0001 ...
7/2/2022 13:00  7/2/2022 14:00  25823-0001 ...
7/2/2022 14:00  7/2/2022 15:00  25823-0001 ...
7/2/2022 15:00  7/2/2022 16:00  25823-0001 ...
7/2/2022 16:00  7/2/2022 17:00  25823-0001 ...
7/2/2022 17:00  7/2/2022 18:00  25823-0001 ...

25823-0001_202208.txt 将包含

8/1/2022 18:00  8/1/2022 19:00  25823-0001 ...
8/1/2022 19:00  8/1/2022 20:00  25823-0001 ...
8/1/2022 20:00  8/1/2022 21:00  25823-0001 ...
8/1/2022 21:00  8/1/2022 22:00  25823-0001 ...
8/1/2022 22:00  8/1/2022 23:00  25823-0001 ...
8/1/2022 23:00  8/2/2022 0:00   25823-0001 ...
8/2/2022 0:00   8/2/2022 1:00   25823-0001 ...
8/2/2022 1:00   8/2/2022 2:00   25823-0001 ...

我目前使用此代码来拆分文件:

foreach($file in $source){
  $fileIn = New-Object IO.StreamReader $file
  #$header = $fileIn.ReadLine()
while ($line = $fileIn.ReadLine())
  {
    $newFile = \"$(($line -split \"\\t\")[2]).txt\"
    if ($newFile -ne $currentFile)
      {...

我尝试将代码编辑为此:

$newFile = \"$(($line -split \"\\t\")[2,0]).txt\"

但显然,由于日期字段的格式,这将不起作用。

    标签: powershell csv text


    【解决方案1】:

    首先将行拆分为一个变量,然后使用DateTime 类解析并重新格式化日期:

    $fields    = $line -split '\t'
    $namePart1 = $fields[2]
    $date      = [DateTime]::ParseExact($fields[0], 'M\/d\/yyyy h\:m', [CultureInfo]::InvariantCulture)
    $namePart2 = $date.ToString('yyyyMM')
    $newFile   = "${namePart1}_$namePart2"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多