陷入了这个PS脚本

时间:2019-05-20 01:30:33

标签: powershell

我有一个包含数百万条记录的文本文件 我想从不是以字符串+该行号开头的每一行中找出(字符串以双引号01/01/2019开头)

您能帮我修改此代码吗?

Get-Content "(path).txt" | Foreach { if ($_.Split(',')[-1] -inotmatch "^01/01/2019") { $_; } }

谢谢

3 个答案:

答案 0 :(得分:0)

根据您的评论,内容将类似于数组。 因此,您想阅读内容,对其进行过滤并从该内容中获取结果行:

{
  "message": "API rate limit exceeded for 116.73.235.229. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)",
  "documentation_url": "https://developer.github.com/v3/#rate-limiting"
}

如果性能成为问题,那么.net将像CsvHelper一样使用PowerBi处理数百万条记录。

# Get the content

# $content = Get-Content -Path 'pathtofile.txt'
$content = @('field1,field2,field3', '01/01/2019,b,c') 

# Convert from csv
$csvContent = $content |  ConvertFrom-Csv 

# Add your filter based on the field
$results = $csvContent | Where-Object { $_.field1 -notmatch '01/01/2019'}  | % { $_ }

# Convert your results back to csv if needed
$results | ConvertTo-Csv

答案 1 :(得分:0)

看着问题和评论,您正在处理的似乎是无标题的CSV文件。因为文件包含数百万条记录,所以我认为使用Get-ContentImport-Csv可能会减慢速度。这样,使用[System.IO.File]::ReadLines()就会更快。

如果确实每一行都以引号引起来,则可以使用各种方法来确定行是否以"01/01/2019开头。在这里,我使用-notlike运算符:

$fileIn  = "D:\your_text_file_which_is_in_fact_a_CSV_file.txt"
$fileOut = "D:\your_text_file_which_is_in_fact_a_CSV_file_FILTERED.txt"

foreach ($line in [System.IO.File]::ReadLines($fileIn)) {
    if ($line -notlike '"01/01/2019*') {
        # write to a NEW file
        Add-Content -Path $fileOut -Value $line
    }
}


更新

从您的评论来看,您显然正在使用旧的.NET框架,因为[System.IO.File]::ReadLines()version 4.0开始可用。

在这种情况下,以下代码应为您工作:

$fileIn  = "D:\your_text_file_which_is_in_fact_a_CSV_file.txt"
$fileOut = "D:\your_text_file_which_is_in_fact_a_CSV_file_FILTERED.txt"

$reader = New-Object System.IO.StreamReader($fileIn)
$writer = New-Object System.IO.StreamWriter($fileOut)
while (($line = $reader.ReadLine()) -ne $null) {
    if ($line -notlike '"01/01/2019*') {
        # write to a NEW file
        $writer.WriteLine($line)
    }
}
$reader.Dispose()
$writer.Dispose()

答案 2 :(得分:0)

我的.txt文件如下所示...

日期,col2,col3
“ 01/01/2019 22:42:00”,“ column2”,“ column3”
“ 01/02/2019 22:42:00”,“ column2”,“ column3”
“ 01/01/2019 22:42:00”,“ column2”,“ column3”
“ 02/01/2019 22:42:00”,“ column2”,“ column3”

此命令完全符合您的要求...

Get-Content -Path C:\myFile.txt | ? {$_ -notmatch "01/01/2019"} | Select -Skip 1

输出为:

“ 01/02/2019 22:42:00”,“ column2”,“ column3”
“ 02/01/2019 22:42:00”,“ column2”,“ column3”

我跳过了第一行。如果要处理特定的列,请将myFile.txt更改为.csv并导入。

相关问题