cmd: Find first letter from a string

9,896

You can get a substring by using the ~n,m syntax on a variable.

Setlocal EnableDelayedExpansion

for /f "tokens=1" %%a in (symantecUsers.txt) do (
    set userid=%%a
    echo The first character is !userid:~0,1!
)
Share:
9,896

Related videos on Youtube

Jineet Vora
Author by

Jineet Vora

Pursuing Masters in Computer Science.

Updated on September 18, 2022

Comments

  • Jineet Vora
    Jineet Vora over 1 year

    I've no knowledge regarding cmd programming syntax. I have a text file containing user IDs which I need to delete using curl command and for that I need to extract first character of every user ID and then pass to the curl command. I know the curl command which I will require two variables:

    1. 'UserID' - Read from the text file.
    2. 'firstCharacter' - Extracting first character from the User ID.

    Below is the code to fetch user IDs from symantecUsers.txt file:

    @echo off
    for /f "tokens=*" %%a in (symantecUsers.txt) do call :processline %%a
    pause
    goto :eof
    :processline
    echo %*
    goto :eof
    :eof
    

    Please help me with extracting the first character from the read User IDs. Thanks.

    • JosefZ
      JosefZ about 8 years
    • aschipfl
      aschipfl about 8 years
      So you are still working with MS-DOS, the OS from the 1980s?
    • Jineet Vora
      Jineet Vora about 8 years
      @aschipfl haha... yeah have no other option... wanted to go with an easier way...
  • Jineet Vora
    Jineet Vora about 8 years
    This works for echo but how do I store this in a variable?
  • Berend
    Berend about 8 years
    The same way: set firstchar=!userid:~0,1!
  • Berend
    Berend about 8 years
    @erreka That probably depends on how you define DOS :-)