Remove pattern from end of line?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
greenfinch
Posts: 36
Joined: 17 Jul 2008 07:37

Remove pattern from end of line?

#1 Post by greenfinch » 17 Jul 2008 08:06

Hello all,

I have a list of text lines I want to process, with names like:
Line Example - (junk)
Line Example - [junk]
Line Example [junk]
Line Example (version2) [junk]

I want to reformat these names and remove the last occurrence of any of the following:
[rest of the line
(rest of the line
- rest of the line

So in the list before, I would get 'Line Example' but the last one would preserve 'Line Example (version2)'

I suppose I need something to work backwards from the end of the line, using the first instance of any of the following as a delimiter:
- or ( or [

Can this be done?

thanks,
GF

greenfinch
Posts: 36
Joined: 17 Jul 2008 07:37

#2 Post by greenfinch » 17 Jul 2008 10:24

An inspiring session of washing the dishes led to the idea that I need to reverse the input string, then I can use FOR on it with delims of [(-

Reverse it again and voila!

Code: Select all

SETLOCAL 

CALL :reverse %1
FOR /f "tokens=1* delims=[(-" %%a in ("%reverse%") DO SET output=%%b

REM strips leading/trailing space
FOR /f "tokens=* delims= " %%a in ("%output%") DO SET output=%%a
CALL :reverse "%output%"

GOTO done

:Reverse
:: Subroutine that reverses the specified input string
:: Initialize variables
SET reverse=
SET input=%~nx1
:Loop
:: Continue till the input string's last character
IF NOT DEFINED input GOTO:EOF
:: Separate first character from input string
SET FirstChar=%Input:~0,1%
SET input=%input:~1%
:: Rebuild string in reverse order
SET reverse=%FirstChar%%reverse%
:: Next character
GOTO Loop

:done

ECHO '%output%'
ECHO '%reverse%'

Post Reply