Mark Pelletier
Mark Pelletier

Reputation: 1359

Batch: Test for Substring in a Variable

I have found a functional approach to identify a substring within a variable (see below ===========). It seems a rather cumbersome way to perform simple InStr() type function.

Is there a better way?

@echo off
setlocal enabledelayedexpansion

::Metadata Creation ::
set File1=filelist.txt
set File2=filelist2.txt

cd\users\mark\downloads\media
::List current \Media files
dir /s/b *.mp4 *.mkv *.m4v > %File1%

::Write metadata
for /f "tokens=*" %%a in (%File1%) do ( 

  :: Full path, no filename
  set myPath=%%~dpa

  :: Parent folder
  for %%b in ("!myPath:~0,-1!") do set "myParent=%%~Nb"

rem ==InStr() type function============

  :: If myParent variable contains the substring, replace
  Set stemp=!myParent!
  Set sstr=photo
  Set pos=0
  :loop
  Set /a pos+=1
  echo !stemp!|FINDSTR /i /c:!sstr! >NUL
  if errorlevel 1 (
     Set stemp=!stemp:~1!
     if defined !stemp! GOTO loop
     Set pos=0
  )
  if !pos! NEQ 0 (set myParent=Photo_Podcast)

rem =============================

Upvotes: 0

Views: 100

Answers (1)

Scott C
Scott C

Reputation: 1660

I think you've overcomplicated things, you have the start of your answer. If you don't care about where in the string the other string is, there is no need for the loop.

echo !myParent!|FINDSTR /i /c:"photo" >NUL
if %errorlevel% equ 0 set myParent=Photo_Podcast

also, you might want to consider making the query: "\photo\" if you are trying to pick up just a folder called photo. Depends what is in myParent of course.

Upvotes: 1

Related Questions