我手头有一个日志文件,看起来像这样: 0226 111641 (1911) 0一些空格分隔的消息,其中包含任何字母和标记
我需要将其导入到数据库中,以便在需要故障排除时对其使用过滤器。目前,我认为powershell是实现这一目标的最佳选择,但我太生疏了,不知道具体怎么做,这样它才能真正发挥作用。我试着这样做:
$file = Get-Content "test.txt"
foreach ($line in $file)
{
#Write-Host $line
$a = $line
$month1 = $a[0..1]
$month2 = "$month1"
$month2 = $month2.ToString()
$month = $month2.Replace(" ", "")
$day1 = $a[2..3]
$day2 = "$day1"
$day2 = $day2.ToString()
$day = $day2.Replace(" ", "")
}..。诸若此类。然后将其插入到数据库中。然而,日志文件相当大(目前3周内为15MB,预计在几个月内将达到数百兆字节),并且脚本已经需要大约4-5分钟来处理它。所以我需要的方法是从行的开头拆分四个空格分隔的列,将第一个和第二个转换为日期和时间,并将它们与该行的消息部分一起添加到数据库中。单独处理每个文本块似乎太耗时了,例如excel可以在几秒钟内处理此文件。是否有一些位置感知的csv-import命令?
谢谢。
我找到了这个:如果我使用linux,Replace first two whitespace occurrences with a comma using sed会有帮助的。:(
发布于 2012-03-21 03:08:48
我不确定ConvertFrom-Csv或Import-Csv cmdlet是否可以帮助您,因为您的字段分隔符可能会出现在message字段中。在不知道这些不同的字段是什么的情况下,我想出了这个:
$file = Get-Content "test.txt"
foreach ($line in $file)
{
# Split $line into at most 5 fields
$fields = $line -split ' ', 5;
# fields[0] is a two-digit month followed by a two-digit day
$date = [DateTime]::ParseExact($fields[0], 'MMdd', $null);
$field2 = $fields[1];
$field3 = $fields[2];
$field4 = $fields[3];
$message = $fields[4];
# Process variables here...
}使用您为$line提供的示例文本,上面的变量在执行后如下所示:
PS> Get-Variable -Name @('date', 'field*', 'line', 'message')
Name Value
---- -----
date 2/26/2012 12:00:00 AM
field2 111641
field3 (1911)
field4 0
fields {0226, 111641, (1911), 0...}
line 0226 111641 (1911) 0 some space separated message
message some space separated message您需要更多关于数据格式的信息,以便为您提供更具体的答案。
https://stackoverflow.com/questions/9790019
复制相似问题