用于过滤 csv 文件中记录的批处理脚本命令

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

我有一个 CSV 文件,格式如下

Input file

我需要一个具有以下过滤条件的新文件到 csv 文件

  1. 过滤掉所有的度量值<=0
  2. 如果度量值>1,则将行复制度量值的次数,并为每个复制记录将日期时间字段的值增加 1 秒,并将度量值重置为 1。

预期结果为output

有人可以帮忙吗?

我试过这个

@echo off
setlocal enabledelayedexpansion

set input_file=input.csv
set output_file=output.csv

(for /f "usebackq tokens=*" %%a in ("%input_file%") do (
    set line=%%a
    set measure values=!line:*,=!
    if "!measure values!" gtr "0" (
        echo !line!
    )
)) > "%output_file%"

我试过上面的脚本,但它将整个记录复制到输出文件中。

csv batch-file
1个回答
0
投票

我不知道批处理文件是最好的但是:

@echo off
setlocal enabledelayedexpansion

set input_file=input.csv
set output_file=output.csv

(
    REM Loop through the lines of the input file, splitting each line into tokens using commas as delimiters.
    for /f "usebackq tokens=1-4 delims=," %%a in ("%input_file%") do (
        call :set_variables "%%a" "%%b" "%%c" "%%d"
        
        REM Check if the value is greater than 1.
        if !value! gtr 1 (
            REM Loop from 1 to the value, incrementing by 1 each time.
            for /l %%i in (1, 1, !value!) do (
                set /a seconds=%%i - 1
                REM Call the subroutine to add seconds to the date and time and set the new_datetime variable.
                call :add_seconds_to_datetime !datetime! !seconds!
                REM Output the new row with the updated date and time and a value of 1.
                echo !new_datetime!,!measure!,!category!,1
            )
        )
    )
) > "%output_file%"

exit /b

:set_variables
set "datetime=%~1"
set "measure=%~2"
set "category=%~3"
set "value=%~4"
goto :eof

REM Subroutine to add seconds to a date and time string in MM/DD/YYYY HH:mm:ss format.
:add_seconds_to_datetime
setlocal
set datetime_str=%1
set seconds_to_add=%2

REM Split the date and time string into date and time.
for /f "tokens=1-2 delims= " %%d in ("%datetime_str%") do (
    set date=%%d
    set time=%%e
)

REM Combine the date and time into an ISO 8601 format.
set "datetime_fmt=!date!T!time!"

REM Use PowerShell to parse the date and time, add the specified number of seconds, and output the new date and time in MM/DD/YYYY HH:mm:ss format.
for /f %%t in ('powershell -noprofile -command "&{[datetime]::ParseExact('%datetime_fmt%', 'MM/dd/yyyyTHH:mm:ss', $null).AddSeconds(%seconds_to_add%).ToString('MM/dd/yyyy HH:mm:ss')}"') do (
    set new_datetime=%%t
)

REM Set the new_datetime variable in the parent scope and exit the subroutine.
endlocal & set "new_datetime=%new_datetime%"
exit /b
© www.soinside.com 2019 - 2024. All rights reserved.