1

My trouble is to read a string from test.txt and type it in as a console command.

Example: user is asked to provide a path to their sandbox folder and at the same time in a console it is already offered (from a saved test.txt), only waiting for the user to hit ENTER

Path to your sandboxes folder: C:\Whatever\Path\Sandboxes

Where Path to your sandboxes folder: is part of a set /p command in a script waiting for an input; and C:\Whatever\Path\Sandboxes has been typed-in by the script as a pre-offered path. From here the user can either hit ENTER, if satisfied with offered path or edit it: C:\Whatever\OtherPath\Sandcastles

I assume, the first step would be to read from test.txt into a variable, but how do I proceed from there? How do i type the characters of this string variable into a console?

  • Unless you can handle single letter commands you need to display the string using `echo` then if the user enters nothing use the displayed string. – ACatInLove Feb 26 '18 at 09:52

3 Answers3

1

By combining it with cscript.

@if (@CodeSection == @Batch) @then

@echo off
for /f "tokens=* delims=" %%i in (test.txt) do set "output=%%I"
  CScript //nologo //E:JScript "%~F0" "%output%"
  set /P "var=Path to your sandboxes folder: "
  echo selected path = %var%
  goto :EOF

@end

WScript.CreateObject("WScript.Shell").SendKeys(WScript.Arguments(0));
Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • Worked like charm! `""%%i""` always created additional `""""` when tested with empty user input, but in general, it's perfect. Thanks! – snakePlantLeaf Feb 26 '18 at 14:21
  • @ClarkYeah I amended the script to not do the double quotes when no variable is selected from file. – Gerhard Feb 26 '18 at 14:34
0

not possible with pure batch, but you can use a default value (because set /p doesn't touch the variable, when you just press ENTER):

for /f "tokens=1,* delims=:" %%a in (test.txt) do (
  set "folder=%%b"
  set /p "folder=%%a (ENTER for default [%%b]) : "
)
echo "%folder%"

Note: there is a space at the start of the %folder%. Easy to avoid, when you remove the space from test.txt:

Path to your sandboxes folder:C:\Whatever\Path\Sandboxes
Stephan
  • 53,940
  • 10
  • 58
  • 91
-2

If in said test.txt the first line only contains the default path, you could use this:

SET /P _path=<test.txt
SET /P _path=%_path%

This is the fastest way to achieve this, but it only works with the 1st line (read more).


If it is e.g. in the 3rd line use this:

FOR /F "skip=2 delims=" %%G IN ("C:\adjust\path\test.txt") DO (SET "_path=%%G" & GOTO break)
:break

SET /P _path=%_path%

For the 5th line change skip=2 to skip=4, for the 17th line to skip=16; basically if the path is in line n you want to skip n-1 lines.

You could also use FINDSTR, but this is unecessary as long as the location of the path in test.txt is known.

FatalBulletHit
  • 762
  • 6
  • 22