简体   繁体   中英

Windows Batch - Get the second line from file and save it

I have a .csv file (source.csv) which has the following contents:

_Name_;_Id_
IQ-000011;a0A4E000001m9UeUAI
IQ-000010;a0A4E000001m9EhUAI
IQ-000009;a0A4E000001m7v5UAA

What I want is either to get the second line (the one starting with IQ-000011 ) to be appended to another file (target.csv) or a new file to be created which consists of the first two lines (The _Name_;_Id_ header + the IQ-000011 line). This has to be done through batch on a Windows 10 machine.

I have tried using set /p and the script below but it didn't work correctly. I want to do it without set /p . How do I accomplish that?

This is the script I tried using:

3<source.csv (
set /p line1= <&3
set /p line2= <&3
)
echo %line2% >> target.csv

I cannot tell by your question, but is this what you're trying to achieve?

@Set "line2="&((Set/P "="&Set/P "line2=")<"source.csv") 2>Nul
@If Defined line2 (Set/P "=%line2%"<Nul&Echo=)>>"target.csv"

Because you could probably do that like this from a batch file, without using Set /P :

@For /F "UseBackQ Skip=1 Delims=" %%A In ("source.csv")Do @(Echo=%%A)>>"target.csv"&Exit/B

Here is a command that will produce the first data line of the .csv file.

FOR /F "delims=" %%a IN ('powershell -NoL -NoP "(Get-Content '.\source.csv')[1]"') DO (SET "LINE2=%%~a")
ECHO LINE2 is set to %LINE2%

Another way that might be more obvious is to use Select-Object to get the desired line.

FOR /F "delims=" %%a IN ('powershell -NoL -NoP "Get-Content '.\source.csv' | Select-Object -Skip 1 -First 1"') DO (SET "LINE2=%%~a")

Of course, if the script is written in PowerShell, it is easier and more clear.

$line2 = (Get-Content '.\source.csv')[1]
$line2 = Get-Content '.\source.csv' | Select-Object -Skip 1 -First 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM