Search code examples
batch-filecmd

Batch script - how to find string that start with another string


In a batch script, I want to move over every line from a text file, and find if it starts with some string (which I don't know the length of it)

set _start_string=whatever
for /f "tokens=*" %%a in (C:\file.txt) do (
  echo _line=%%a
  if **\_line start with _start_string\** do (echo %_line%)
  )

here need to search which _line starts with _start_string, only the if the condition is missing.


Solution

  • I'll explain what I wrote in my comment here.

    First the only way to compare a part of a string is by using the findstr command. You can use the answer here https://stackoverflow.com/a/23170295/20499460 if you want or just use the code below (it should work but i can't test it) :

    1- remove your if :

    if **\_line start with _start_string\** do (echo %_line%)
    

    2- correct you echo to a set (it looks like a mistake) :

    set _line=%%a
    

    3- change it for the line :

    echo %%a | findstr /b %_start_string% >nul 2>&1 && (echo %%a)
    

    So you print your line : echo %%a, search for the string _start_string at the start of the line (with the findstr and the /b option).

    AND if everything worked correctly, print the line.

    The >nul 2>&1 is just here to remove all the output of the findstr and only keep what is after the &&

    Hope this helps ! Feel free to ask further questions :)