Reading from a csv file and extracting certain data columns based on first column value

前端 未结 4 571
情书的邮戳
情书的邮戳 2021-02-08 03:45

This is my first batch program and I have been searching online but still struggling to write up a solution.

I have the following CSV file:

\"RH\",2013/0         


        
4条回答
  •  -上瘾入骨i
    2021-02-08 04:24

    (
    FOR /F "tokens=1-18* delims=," %%A IN (%_InputFile%) DO (
      if "%%~A"=="RH" echo %%~B
      if "%%~A"=="SH" echo %%~D
     )
    )>youroutputfilename
    

    Should work - no need to assign all the values to different variables - BUT if you plan to use them, then

    FOR /F "tokens=1-18* delims=," %%A IN (%_InputFile%) DO (
    ...
    Set _var17=%%Q
    Set _var18=%%R
    CALL :PROCESS
    )
    ...
    GOTO :EOF
    
    :PROCESS
    IF %_var1%=="RH" echo %_var2%
    IF %_var1%=="SH" echo %_var4%
    GOTO :EOF
    

    Note that with this method, since you are assigning %%x to _varx then if %%x is quoted, the quotes will be INCLUDED in the value assigned. To remove the enclosing quotes (if they exist) use SET _varx=%%~x.


    Addendum 20130703-1956Z for OP's problem

    @ECHO OFF
    SETLOCAL
    SET _Inputfile=u:\noname1.txt
    (
    FOR /F "tokens=1-18* delims=," %%A IN (%_InputFile%) DO (
      SET "RH="
      SET "SH="
      ECHO(%%A|FINDSTR /l /c:"\"RH\"" >NUL
      IF NOT ERRORLEVEL 1 SET RH=Y
      ECHO(%%A|FINDSTR /l /c:"\"SH\"" >NUL
      IF NOT ERRORLEVEL 1 SET SH=Y
      if DEFINED RH echo %%~B
      if DEFINED SH echo %%~D
     )
    )>u:\youroutputfilename
    TYPE u:\youroutputfilename
    del u:\youroutputfilename
    echo========First way
    
    (
    FOR /F "tokens=1-18* delims=," %%A IN (%_InputFile%) DO (
      SET _var1=%%A
      SET "RH="
      SET "SH="
      CALL :process
      if DEFINED RH echo %%~B
      if DEFINED SH echo %%~D
     )
    )>u:\youroutputfilename
    
    TYPE u:\youroutputfilename
    del u:\youroutputfilename
    echo========Second way
    
    SETLOCAL ENABLEDELAYEDEXPANSION 
    (
    FOR /F "tokens=1-18* delims=," %%A IN (%_InputFile%) DO (
      SET _var1=%%A
      IF "!_var1:~-4!"==""RH"" echo %%~B
      IF "!_var1:~-4!"==""SH"" echo %%~D
     )
    )>u:\youroutputfilename
    
    TYPE u:\youroutputfilename
    del u:\youroutputfilename
    echo========Third way
    ENDLOCAL
    
    GOTO :EOF
    
    :process
    IF "%_var1:~-4%"==""RH"" SET RH=Y
    IF "%_var1:~-4%"==""SH"" SET SH=Y
    GOTO :EOF
    

提交回复
热议问题