从bat文件中的txt中选择信息

问题描述 投票:1回答:2

有一个文本文件,它以以下格式存储已处理文件的日志:

名称:kn-25.txt日期:2013年1月2日时间:14:50

任务是编写一个批处理文件,该文件将从文件中选择给定月份(mm)和年份(yyyy)到文件result.txt中。按处理日期对生成的文件进行排序。

@echo off
chcp 1251 >nul
setlocal EnableDelayedExpansion
echo Введіть перший параметр: 
set /p in_file=%~f1
if [%in_file%] == [] goto end

set /a count=0
set /a min=0
set /p month=Введіть місяць:
if [%month%] == [] goto end 
set /p year=Введіть рік:
if [%year%] == [] goto end 

for /f "tokens=*" %%i in (%in_file%) do (
    for /f "tokens=1-6" %%a in (%%~i) do (
        for /f "delims=. tokens=1-3" %%u in (%%~d) do (
            if "%%v"=="%month%" if "%%w"=="%year%" if "%%u" GTR "!min!" (
                  set /a count=count+1
                  set /a min=!min!+1
                  echo !count!. %%i>D:\result.txt
            )       
        )   
    )
)

type D:\result.txt
echo 
@pause
endlocal

:end
echo Ви не ввели параметр!
echo   
@pause
endlocal

我写了这段代码,但出现错误:

找不到文件名:。

有什么建议吗?

batch-file cmd
2个回答
0
投票
@echo off
chcp 1251 >nul
setlocal EnableDelayedExpansion
echo Введіть перший параметр: 
set /p in_file=%~f1
if not exist %in_file% goto end


set /p month=Введіть місяць:
if [%month%] == [] goto end
set /p year=Введіть рік:
if [%year%] == [] goto end 

findstr /C:"%month%.%year%" %in_file% > D:\result.txt

type D:\result.txt 
pause
exit /B

:end
echo Ви не ввели параметр! 
pause
exit /B

0
投票

如果您使用的是受支持的Windows计算机,则将使用PowerShell。这是一种方法。假定日期为DD.MM.YYYY格式。

由于已经使用正则表达式解析了日期和时间,因此它创建了一个[DateTime]与日志文件行关联。然后,它使用此[DateTime]对文件进行排序,但仅输出日志文件行。

[CmdletBinding()]
param (
    [Parameter(Mandatory=$true,Position=0)]
    [string]$LogFile
    ,[Parameter(Mandatory=$true,Position=1)]
    [int]$Year
    ,[Parameter(Mandatory=$true,Position=2)]
    [int]$Month
)

Get-Content -Path $LogFile |
    ForEach-Object {
        if ($_ -match 'Name: .* Date: ((\d*)\.(\d*)\.(\d*)) Time: ((\d*):(\d*))') {
            #$Matches
            $fday = [int]$Matches[2]
            $fmonth = [int]$Matches[3]
            $fyear = [int]$Matches[4]
            $fhour = [int]$Matches[6]
            $fminutes = [int]$Matches[7]
            if (($fmonth -eq $Month) -and ($fyear -eq $Year)) {
                [PSCustomObject]@{
                    Line = $_
                    Timestamp = Get-Date -Year $fyear -Month $fmonth -Day $fday `
                        -Hour $fhour -Minute $fminutes -Second 0
                }
            }
        }
    } |
    Sort-Object -Property Timestamp |
    ForEach-Object { $_.Line }

使用以下命令调用它。如果不提供参数,PowerShell将提示您输入参数。就像在cmd.exe bat文件脚本中使用SET /P

.\logparse.ps1 -LogFile '.\logparse.in.txt' -Year 2013 -Month 2
© www.soinside.com 2019 - 2024. All rights reserved.