Use SED to extract part of a line?

Microsoft Windows
Rekrul
Posts: 52
Joined: 2021-Aug-15, 11:29 pm

Re: Use SED to extract part of a line?

Post by Rekrul »

And once again, I found bugs and shortcomings in my script. It wasn't correctly counting the NZB files in the directory if run from an open window because the set command to clear the variable was in the wrong place. It also didn't correctly recognize filenames with exclamation points due to my using the wrong variable tags. Also I used delayed expansion for another part that (apparently) doesn't need it.

So here's my latest version;

Code: Select all

@echo off
title Fix NZBKing Files

set CurrentFile=1
set Tag=)\"^>
set ListLines=0
set NZBCount=0

if "%1"=="" goto ProcessAll

set List=%1

for /f %%F in (%List%) do (set Filename=%%F
call :NameCheck)

if %ListLines% equ 0 goto :ProcessAll
if %NZBCount% equ 0 goto:eof

for /f "delims=" %%F in (%List%) do (set Filename=%%F
call :ProcessNZB)
goto:eof

:ProcessAll
for %%F in (*.nzb) do set /a NZBCount=NZBCount+1
for %%F in (*.nzb) do (set Filename=%%F
call :ProcessNZB)
goto:eof

:ProcessNZB
if not "%Filename:~-4%"==".nzb" exit /b

for /f %%E in ('grep -c "<file poster=" "%Filename%"') do set FilesCount=%%E
setlocal enabledelayedexpansion
for /f %%E in ('grep -c "!Tag!" "!Filename!"') do endlocal & set FixedCount=%%E
if %FixedCount% equ %FilesCount% (echo Skipping: %Filename%
set /a CurrentFile=CurrentFile+1
exit /b)

md Originals 2>nul

setlocal enabledelayedexpansion
echo !Filename!
endlocal
copy "%Filename%" Originals\ >nul

set Counter=1
for /f "tokens=1 delims=:" %%E in ('grep -no "<file poster=" "%Filename%"') do (set Value=%%E
call :ArrayIn Subject
call :IncrementCounter)

set Counter=1
for /f "tokens=1 delims=:" %%E in ('grep -no "</segments>" "%Filename%"') do (set /a Value=%%E-1
call :ArrayIn LastPart
call :IncrementCounter)

set Counter=1
:FixNZB
call :ArrayOut Subject
set SubjectLine=%Value%

call :ArrayOut LastPart
set LastPartLine=%Value%

for /F tokens^=4^ delims^=^" %%P in ('sed -n "%LastPartLine%,%LastPartLine%p" "%Filename%"') do set LastPartNumber=%%P

sed "%SubjectLine%s/ \"^>/ (1\/%LastPartNumber%)\">/" "%Filename%" >Temp.tmp
del "%Filename%"
ren Temp.tmp "%Filename%"
title Fix NZBKing Files - Processing file %CurrentFile% of %NZBCount% - %Counter% of %FilesCount% headers fixed
call :IncrementCounter

if %Counter% leq %FilesCount% goto FixNZb
ren "%Filename%" "%Filename:~0,-4%-Fixed.nzb"
set /a CurrentFile=CurrentFile+1
exit /b

:ArrayIn
set ArrayName=%1
call :Array2 %ArrayName%[%Counter%] %Value%
exit /b
:ArrayOut
set ArrayName=%1
call :Array2 Value %%%ArrayName%[%Counter%]%%
exit /b
:Array2
set %1=%2
exit /b

:IncrementCounter
set /a Counter=Counter+1
exit /b

:NameCheck
set /a ListLines=ListLines+1
if "%Filename:~-4%"==".nzb" set /a NZBCount=NZBCount+1
exit /b
Post Reply