for loop - Extract Part of a text file in BAT -
i capturing m3u file on daily basis wish parse part of file few channels need.
for example have renamed m3u test.txt file has following fictional structure:
#extinf:0,abc #live link 1 #extinf:0,xyz #live link 2 #extinf:0,uvw #live link 3
i capture line staring "#extinf:0,xyz" , line beneath end output.txt follows:
#extinf:0,xyz #live link 2
i know 1 needs use loop bit of noob on area.
i this, supposing .m3u
file not contain trailing white-spaces in lines preceded #extinf
, sample data does:
@echo off setlocal enableextensions disabledelayedexpansion rem // define constants here: set "file=%~1" set "header=#extm3u" set "prefix=#extinf" set "match=%~2" set "flag=" /f usebackq^ delims^=^ eol^= %%l in ("%file%") ( if defined flag ( echo(%%l set "flag=" ) /f "delims=:" %%p in ("%%l") ( if "%%p"=="%header%" ( echo(%%l ) else if "%%p"=="%prefix%" ( set "line=%%l" setlocal enabledelayedexpansion if /i "!line:*,=!"=="!match!" ( echo(!line! endlocal set "flag=#" ) else endlocal ) ) ) endlocal exit /b
call script this, supposing saved extract-entry.bat
:
extract-entry.bat "input_file.m3u" "xyz" > "output_file.m3u"
the script walks through given .m3u
file line line. returns current line unedited , resets variable flag
, if variable flag
set, not case @ beginning.
then looks #extinf
. if found (e. g., #extinf:0,xyz
), string after comma (xyz
) compared against given search string. if matched, current line output , flag
variable set in order following line too.
the header line #extm3u
output.
toggling delayed expansion makes script robust against characters have special meaning command interpreter without losing them.
Comments
Post a Comment