1

I have a .txt file containing D: random text and I want to select from the .txt file only the first 2 letters as the content of a variable (in CMD):

echo D: random text > C:\Users\%USERNAME%\textfile.txt

Expected:

echo %variable%
"D:"
Compo
  • 36,585
  • 5
  • 27
  • 39
  • 1
    `for /f %a in (C:\Users\%USERNAME%\textfile.txt) do set "var=%a"`. See `for /?` for details. – Stephan Jul 31 '19 at 07:44
  • @Stephan's command will get you the 1st space/tab separated word from the last line of the file. To be more precise to your demand use `set /p "variable="<"C:\Users\%USERNAME%\textfile.txt"` and `set "variable=%variable:~0,2%"` –  Jul 31 '19 at 08:31
  • 2
    @LotPings: yes. The file has only one line (see how it's generated) and the first two characters are followed by a space. Yours is more generic, but takes the first two letters of the first line of the file (doesn't matter, if LastLine = FirstLine). As the question stands, both approaches are valid. – Stephan Jul 31 '19 at 08:41
  • I'd do this: `< "%UserProfile%\textfile.txt" set /P Variable=""`, then `echo(%Variable:~,2%`... – aschipfl Jul 31 '19 at 09:10
  • Related: [Store file output into variable](https://stackoverflow.com/q/4584189)... – aschipfl Jul 31 '19 at 09:15
  • Thanks all to answers. All solutions were successfuls – JaroslavKucera Jan 17 '21 at 23:06

0 Answers0