2

How do I cut strings like these in my .bat file as soon as the string , TARO/ appears?

Init., 12, TARO/ BLA BLA CDE
Ademanto, TARO/ BLA BLA XYZ

I only want to have Init., 12 and Ademanto afterwards.

I cannot use the delimiter in FOR, as it is limited to only one single character, right?

Mofi
  • 46,139
  • 17
  • 80
  • 143
mifu
  • 33
  • 1
  • 5

3 Answers3

6

set is able to cut from beginning to a defined string, but not from a defined string to the end. Using a little trick helps:

setlocal enabledelayedexpansion
set "string=Init., 12, TARO/ BLA BLA CDE" 
set "str=%string:*TARO/=TARO/%"
echo "!string:%str%=!"

(replace start of string including the delimiter-string (*TARO/) with the delimiter string only (TARO/). In a second step, remove the found string)

Another way is to replace the delimiter-string with a single char delimiter (any char that is sure not to be in the string. (The strange symbol below (þ) is a chr(127), but you can also use @, # or any other char that isn't in your string(s))

for /f "delims=þ" %%i in ("%string:TARO/=þ%") do echo %%i
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • as soon as you replace `string1` by `string` in your `echo` command line (ehich I guess is just a typo), your answer works if there are no poisonous characters like `"` or `=` in the initial string, and if it does not start with `*` or `~`... – aschipfl Feb 16 '16 at 00:18
6

There's one other way. Replace , TARO/ with &rem;.

@echo off
setlocal

set "str=Init., 12, TARO/ BLA BLA CDE"
set str=%str:, TARO/=&rem;%

echo %str%

That works because the variable is expanded before the set command is evaluated. So when the line is evaluated, it's evaluated as...

set str=Init.,12&rem; BLAH BLAH CDE

... as a compound command of set var=value & rem (rest of line ignored)

You could also echo %str:, TARO/=&rem;% and achieve the same effect.

rojo
  • 24,000
  • 5
  • 55
  • 101
  • 3
    Should work well as long as the string does not contain quote or poison character before the cutoff string, which is certainly true for the example text. – dbenham Feb 13 '16 at 20:20
5

Here is a more robust solution that should work even if the string contains quotes or poison characters - replace the cutoff string with a new line character. FOR /F will iterate each resultant line, so use GOTO to break out of the loop and preserve just the first line.

@echo off
setlocal disableDelayedExpansion
set "string=;Init., 12, TARO/ BLA BLA CDE"
setlocal enableDelayedExpansion
set ^"string=!string:, TARO/=^

!^"
for /f delims^=^ eol^= %%A in ("!string!") do (
  endlocal
  set "string=%%A"
  goto :break
)
:break
set string
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • too fancy for me. I don't get this one. Sorry. – mifu Feb 15 '16 at 16:47
  • Alright, I've come to my senses. Your solution is much better. Can you adjust it in a way that I can check for several strings, like `, TARO`, `, TARI` and `, TARU`? – mifu Feb 15 '19 at 21:29