How do I check if some string *starts* with a specific word in batch

11,753

This can be done with FINDSTR like this:

FINDSTR "^searchterm"

The ^ at the beginning of a search expression specifies that you are looking for the substring specifically at the beginning of a line.

Note that by default FINDSTR performs a case-sensitive search. To search regardless of letter case, specify the /I switch:

FINDSTR /I "^searchterm"

The source to search can be specified:

  • as a parameter:

    FINDSTR /I "^searchterm" filename
    
  • using stdin redirection:

    FINDSTR /I "^searchterm" < filename
    
  • using piping:

    command | FINDSTR /I "^searchterm"
    

    (in this case, the source is the output of the command)

If you want to search multiple files, particularly if they are in the same directory or directory tree, it is probably easiest to use the first pattern of the above three, because the filename in this case can be a mask:

FINDSTR /I "^searchterm" D:\path\to\files*.ext

The above will search files in the specified directory only. To search the entire tree, i.e. including all the subdirectories, add the /S switch:

FINDSTR /I /S "^searchterm" D:\path\to\files*.ext

Other useful options can be found in the built-in help (run FINDSTR /?).

Share:
11,753
Sigalit
Author by

Sigalit

Updated on July 10, 2022

Comments

  • Sigalit
    Sigalit almost 2 years

    How do I check if some string (line from a text file for the record) starts with a specific word in batch?

    I know how to check if the word (sub-string) exists in the sentence/line (string), But how can I Check Weather it STARTS with this word?

    Thanks :)