0

I want to find every line in a text file that contains the word "foo". I set up my if statement like this...

for /f "delims=" %%i in ('type "%textfile%" ^| find /v /n "" ^& break ^> "%textfile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion


    set "wordtofind=foo"
    if not "!line!"=="!line:!wordtofind!!" (
        set "erase=!line:*=!"
        set "newCode=bar"
        >>"!textfile!" echo !newCode!

For some reason, the if statement executes when the string "value" is found. Can someone please explain why that is?

Narbs
  • 35
  • 1
  • 5
  • What do you think `!line:*=!"` will do? Or `!line:!wordtofind!!`? – Stephan Nov 21 '18 at 16:02
  • I'm new to batch but I thought that it would find "foo" erase the line and then replace it with "bar". But it also finds lines with the string "value" and replaces them with "bar". – Narbs Nov 21 '18 at 16:08
  • I would suggest you forget about using a batch file and choose a language/utility which can modify files directly, will accept regular expressions and where poison characters are less of an issue. – Compo Nov 21 '18 at 16:36
  • Great suggestion... but this has to be in a batch file. – Narbs Nov 21 '18 at 17:18
  • `setlocal enabledelayedexpansion` must be put before a code block. You enabled it when the whole `for /f` block has been passed through variable substitution, which is useless – phuclv Nov 27 '18 at 01:34
  • I now have setlocal enabledelayedexpansion at the top of my code and it still does not work. I also replaced % with !. – Narbs Nov 27 '18 at 14:22
  • Thank you for the help, I found what I needed here... https://stackoverflow.com/questions/7005951/batch-file-find-if-substring-is-in-string-not-in-a-file/7006016#7006016 – Narbs Nov 27 '18 at 15:19

0 Answers0