I'd like to write a batch script that reads a specific word between delimiters:
Eg my text file contains the below
!DATA
Scen|2022|m|YTD|a|b|c|d|e|f|g|h|101
Scen|2022|m|YTD|a1|b1|c1|d1|e1|f1|g1|h1|102
The text file will have around 1000 lines. I will always want to read the 3rd line.
I want to:
1. Get the first word before the pipe delimiter (eg Scen
) and store to some variable
2. I then want the second word between 1st & 2nd pipe marks (eg 2022
)
Any help in this would be great.
CodePudding user response:
Here's an example for you to really get your teeth into:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "targetLine="
( Set /P "="
Set /P "="
Set /P "targetLine="
) 0< "textFile.ext"
If Not Defined targetLine GoTo :EOF
For /F "Delims==" %%G In ('"(Set Field) 2>NUL"') Do Set "%%G="
Set "i=1"
SetLocal EnableDelayedExpansion
Set "Field!i!=%targetLine:|=" & Set /A i =1 & Set "Field!i!=%"
Echo %%Field1%% = %Field1%; %%Field2%% = %Field2%
Pause
The above technique has actually defined a variable for each of the pipe delimited fields. To see those just change line 13
to (Set Field) 2>NUL
(Set /P "var=") 0< "stdInput"
defines var
with the value of the first non empty input line, In this case you would change stdInput
(textfile.ext
) to your actual source file. I have therefore extended the idea to retrieve the third line. I will not explain the creation of the variables for each of the fields, simply link you to an already existing explanation.
CodePudding user response:
- If these are your intended executions:
!DATA // Your Line Skipped: 1
Scen|2022|m|YTD|a|b|c|d|e|f|g|h|101 // Your Line Skipped: 2
Scen|2022|m|YTD|a1|b1|c1|d1|e1|f1|g1|h1|102 // Your Line Strings To Save: Scen & 2022
... // Your Lines Remaining Skipped: Goto %:^)
- A simpler way to do it would be:
@echo off & cd /d "%~dp0"
for /f "usebackq skip=2 delims=| tokens=1-2*" %%i in (`
type InputFile.txt`)do set "_str_1=%%i" && set "_str_2=%%j" & goto %:^)
%:^)
echo\ %%_str_1%% == %_str_1% && echo\ %%_str_2%% == %_str_2%