Only use first word of input batch file - batch-file

I am making a program that needs to run the commands that users put in.
If the command doesn't exist it opens an error.
:cmd
set /p cmd="Command:"
if not exist %cmd% goto nocommand
%cmd%
:noCommand
echo Error, command doesn't exist..
goto cmd
But if I type "echo text" it says text isn't a command. I need it to only read the first word.

Checks if its is possible to execute the command as an internal,from given path or from %PATH%. It uses also solution from dbenham from here : Check if command is internal in CMD
#echo off
:cmd
set /p "cmd=Command:"
for /f "tokens=1 delims= " %%a in ("%cmd%") do set "fcmd=%%~na"
setlocal
set "empty=%temp%\empty%random%"
md "%empty%"
pushd "%empty%"
set path=
>nul 2>nul %fcmd% /?
if not errorlevel 9009 (
popd
rd "%empty%"
echo %fcmd% is internal command
endlocal
goto :execute
) else (
popd
rd "%empty%"
endlocal
)
color
for %%# in (%PATHEXT%;"" ) do (
rem echo --%fcmd%%%~#--
if exist %fcmd%%%~# (
echo the command/executable/script will be executed from given location
goto :execute
)
for /f "tokens=1 delims= " %%a in ("%fcmd%%%~#") do (
if "%%~$PATH:a" NEQ "" (
echo the command/executable/script is defined in %%PATH%%
rem
goto :execute
)
)
)
echo command does not exist
exit /b 1
:execute
%cmd%

set /p cmd="Command:"
for /f "tokens=1" %%i in ("%cmd%") do set firstword=%%i
echo %firstword%

Related

How can I delete last "\" from file's path in batch script

I was trying this, it'll count file's line after I copy the file's path (Shift+right click >copy as path) and put it in batch file, but.... how do I fix it??
the last \ in %path% is causing problem.
#echo off
Setlocal EnableDelayedExpansion
set /p ifilename=Enter file name:
for %%f in (%ifilename%) do (
set paath=%%~df%%~pf
set ifilename=%%~nf%%~xf
)
echo %paath%
echo %ifilename%
for /f "usebackq" %%a in (`dir /b /s %1 "%paath%"`) do (
for /f "usebackq" %%b in (`type %ifilename% ^| find "" /v /c`) do (
set lines= %%b
)
)
echo %lines%
pause
>> the last \ in %path% is causing problem
It's easy to solve this , the code is :
set TempDir=C:\0TEMP
#echo off
md %TempDir%
cd /d %TempDir%
::------
#echo off
#echo on
Setlocal EnableDelayedExpansion
::set /p ifilename=Enter file name:
SET DUMMYexe=%TempDir%\DUMMY.exe
IF EXIST "%DUMMYexe%" goto ll123
ECHO ---------writing
pause
(
ECHO pause1
ECHO pause2
ECHO pause3
) > %DUMMYexe%
:ll123
SET ifilename=%DUMMYexe%
for %%f in (%ifilename%) do (
set fpath=%%~df%%~pf
set ifilename=%%~nf%%~xf
)
echo %fpath%
echo %ifilename%
SET v=asdf1234
SET vv=\%v%
SET vvv=%fpath%%vv%
CALL SET v=%%vvv:\%vv%=%%
echo 111---%v%
pause
set fpath=%v%
for /f "usebackq" %%a in (`dir /b /s %1 "%fpath%"`) do (
for /f "usebackq" %%b in (`type %ifilename% ^| find "" /v /c`) do (
set lines= %%b
)
)
echo %lines%
echo on
pause
goto
But of course, if I use the var 'path', my win10 will report :
'find' is not recognized as an internal or external command, operable program or batch file.
BTW, Maybe you'd be interested in the code below :
SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`dir `) DO (
SET var!count!=%%F
SET /a count=!count!+1
)
ECHO -------------- %count%
ECHO
ECHO %var1%
ECHO %var2%
ECHO %var3%
ENDLOCAL
pause
which I tested after copying from:
How to set commands output as a variable in a batch file
Very useful info about "Setlocal EnableDelayedExpansion" can be found in:
How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

Batch file finding a filename which contains a substring

I want to write a batch file to find all .vsdm files and the file name must contain a substring "2.4". But my code is telling me that all my .vsdm files contains the substring "2.4" which is not correct.
FOR /R %completepath% %%G IN (*.vsdm) DO (
set file=%%~nG
If not "%file%"=="%file:2.4=%" (
echo Filename contains 2.4
) else (
echo Filename does NOT contains 2.4
)
)
Can anyone tell me where did I get it wrong?Thanks
If "%file%"=="%file:2.4=%" (
echo Filename "%file%" does NOT contain 2.4
) else (
echo Filename "%file%" contains 2.4
)
Including the filename in the echo may reveal more. I can see no reason for the double-negative approach. The way the code operates may depend on precisely where in code the instructions are located, for instance if these lines are contained within any variety of loop or code-block, operation may depend on other elements, so it's important to present the code in-context and with an example of what was expected and what actually happened.
correct fomatting makes all clear.
There are one or two SO articles about delayed expansion which OP should become familiar with.
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /R %completepath% %%G IN (*.vsdm) DO (
set "file=%%~nG"
If not "!file!"=="!file:2.4=!" (
echo Filename contains 2.4
) else (
echo Filename does NOT contains 2.4
)
)
ENDLOCAL
You can use the command Where /? that let you use wildcard characters ( ? * ) and UNC paths.
#echo off
Title Find the location of a file with substring by Hackoo
Color 0A
Call :inputbox "Enter the file name to search :" "Enter the file name to search"
If "%input%" == "" Color 0C & (
echo(
echo You must enter a filename to continue with this program
pause>nul & exit
) else (
Call :Browse4Folder "Select the source folder to scan %input%" "c:\scripts"
)
Set "ROOT=%Location%"
::We check whether the input string has an anti-Slach in the end or no ? if yes, we remove it !
IF %ROOT:~-1%==\ SET ROOT=%ROOT:~0,-1%
set whereCmd=where.exe /r %ROOT% %input%
for /f %%a in ('%whereCmd%') do echo %%~nxa --^> %%a
pause & exit
::***************************************************************************
:Browse4Folder
set Location=
set vbs="%temp%\_.vbs"
set cmd="%temp%\_.cmd"
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
(
echo set shell=WScript.CreateObject("Shell.Application"^)
echo set f=shell.BrowseForFolder(0,"%~1",0,"%~2"^)
echo if typename(f^)="Nothing" Then
echo wscript.echo "set Location=Dialog Cancelled"
echo WScript.Quit(1^)
echo end if
echo set fs=f.Items(^):set fi=fs.Item(^)
echo p=fi.Path:wscript.echo "set Location=" ^& p
)>%vbs%
cscript //nologo %vbs% > %cmd%
for /f "delims=" %%a in (%cmd%) do %%a
for %%f in (%vbs% %cmd%) do if exist %%f del /f /q %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
goto :eof
::***************************************************************************
:InputBox
set "input="
set "heading=%~2"
set "message=%~1"
echo wscript.echo inputbox(WScript.Arguments(0),WScript.Arguments(1)) >"%temp%\input.vbs"
for /f "tokens=* delims=" %%a in ('cscript //nologo "%temp%\input.vbs" "%message%" "%heading%"') do (
set "input=%%a"
)
exit /b
::***************************************************************************

Speed up batch code

Can you advice what else I can do for speeding up my batch, please?
Works quite well apart takes ages to finish :)
Sorry for this text but I'm not able to post my question due to the message 'it looks like your post is mostly code bla bla bla. Admin- can you turn this verification OFF!!!
#echo off
c:
cd \
pushd \\ftp\ftp$
cls
echo ________________________________________________________________
echo.
color f9
:WPIS
set /p moje=Please enter required LOGIN NAME:
if exist "\\ftp\ftp\Transfer\%moje%" echo USER ALREADY EXIST TRY ANOTHER ONE && GOTO WPIS
:KOD
set mojep=%random%%random%%random%
setlocal enabledelayedexpansion
set input=default2015.Archive
set output2=%moje%.Archive2
set output1=%moje%.Archive1
set output=%moje%.Archive
set text2searchfor=default2015
set password2searchfor=szukajpassword
set folder2search=F:\\Transfer\\default2015
set newfolder=F:\\Transfer\\%moje%
del %output1%
cls
echo Wait....
for /F "tokens=*" %%f in ('type %input%') do (
set line=%%f
if "!line!"=="%text2searchfor%" (
set NAME=%moje%
echo !NAME!>> %output2%
) else (
echo !line!>> %output2%
)
)
for /F "tokens=*" %%f in ('type %output2%') do (
set line=%%f
if "!line!"=="%folder2search%" (
set NAME=%newfolder%
echo !NAME!>> %output1%
) else (
echo !line!>> %output1%
)
)
for /F "tokens=*" %%f in ('type %output1%') do (
set line=%%f
if "!line!"=="%password2searchfor%" (
set NAME=%mojep%
echo !NAME!>> %output%
) else (
echo !line!>> %output%
)
)
del %output1%
del %output2%
pushd \\ftp\ftp\Transfer\
md %moje%
popd \\ftp\ftp\Transfer\
popd \\ftp\ftp$
...
Try this:
#echo off
c:
cd \
pushd \\ftp\ftp$
cls
echo ________________________________________________________________
echo.
color f9
:WPIS
set /p moje=Please enter required LOGIN NAME:
if exist "\\ftp\ftp\Transfer\%moje%" echo USER ALREADY EXIST TRY ANOTHER ONE && GOTO WPIS
:KOD
set mojep=%random%%random%%random%
setlocal
set input=default2015.Archive
set output2=%moje%.Archive2
set output1=%moje%.Archive1
set output=%moje%.Archive
set text2searchfor=default2015
set password2searchfor=szukajpassword
set folder2search=F:\\Transfer\\default2015
set newfolder=F:\\Transfer\\%moje%
cls
echo Wait....
(for /F "delims=" %%f in (%input%) do (
if "%%f"=="%text2searchfor%" (
echo %moje%
) else (
echo %%f
)
)) > %output2%
(for /F "delims=" %%f in (%output2%) do (
if "%%f"=="%folder2search%" (
echo %newfolder%
) else (
echo %%f
)
)) > %output1%
(for /F "delims=" %%f in (%output1%) do (
if "%%f"=="%password2searchfor%" (
echo %mojep%
) else (
echo %%f
)
)) > %output%
del %output1%
del %output2%
pushd \\ftp\ftp\Transfer\
md %moje%
popd \\ftp\ftp\Transfer\
popd \\ftp\ftp$
If more speed is needed, a much faster solution may be written via a Batch-JScript hybrid script.
This uses a native Windows batch script called Jrepl.bat (by dbenham)
- download from: https://www.dropbox.com/s/4otci4d4s8x5ni4/Jrepl.bat
and it can also be found here: http://www.dostips.com/forum/viewtopic.php?f=3&t=6044
It is significantly faster for large files than plain vanilla for loops.
This assumes that your strings to be replaced are not embedded in any other lines, and just occur by themselves.
As you are changing the directory, placing jrepl.bat on the system path is wise so the script can find it, or hard code the path to jrepl.bat
#echo off
cd /d c:\
pushd \\ftp\ftp$
cls
echo ________________________________________________________________
echo.
color f9
:WPIS
set /p moje=Please enter required LOGIN NAME:
if exist "\\ftp\ftp\Transfer\%moje%" echo USER ALREADY EXIST TRY ANOTHER ONE && GOTO WPIS
:KOD
set mojep=%random%%random%%random%
setlocal enabledelayedexpansion
set input=default2015.Archive
set output2=%moje%.Archive2
set output1=%moje%.Archive1
set output=%moje%.Archive
set text2searchfor=default2015
set password2searchfor=szukajpassword
set folder2search=F:\\Transfer\\default2015
set newfolder=F:\\Transfer\\%moje%
cls
echo Wait....
call jrepl "%text2searchfor%" "%moje%" /L /f %input% /o %output%
call jrepl "%folder2search%" "%newfolder%" /L /f %output% /o -
call jrepl "%password2searchfor%" "%mojep%" /L /f %output% /o -
pushd \\ftp\ftp\Transfer\
md %moje%
popd \\ftp\ftp\Transfer\
popd \\ftp\ftp$

Directory traversal and file selection with .bat

I am trying to write a .bat file that allows me to traverse through directories (up or down) and let me select a file from the current directory, passing that filename out at the end of the routine. Ideally, it would handle if it is at the root of a drive (i.e. C:) or that there are no more sub directories.
(If there are more elegant ways of doing what I am asking, please feel free to suggest them!)
#echo off
setlocal enabledelayedexpansion
set FVAR=
:start
::-------------------------------------------------------
:: LIST - Lists all files in the current folder
::-------------------------------------------------------
:LIST
echo.
if exist . echo ^<DIR^> .
if exist .. echo ^<DIR^> ..
for /f "tokens=* delims=" %%a in ('dir /b /ad') do (
echo ^<DIR^> %%a
)
for /f "tokens=* delims=" %%a in ('dir /b /a-d') do (
echo %%a
)
::-------------------------------------------------------
:: INPUT - Requests filename as input from user
::-------------------------------------------------------
:INPUT
echo.
set /p FVAR="Choose your file [HINT: hit <TAB> to cycle the current folder contents]: "
echo.
echo %FVAR%
if not defined FVAR (goto TRYAGAIN)
set FVARFLAG1=0
set FVARFLAG2=0
set FVARFLAG=%FVARFLAG1%%FVARFLAG2%
echo %FVARFLAG%
if exist %FVAR%\ set "%FVARFLAG1%"=="1"
if exist %FVAR% set "%FVARFLAG2%"=="1"
set FVARFLAG=%FVARFLAG1%%FVARFLAG2%
echo %FVARFLAG%
if "%FVARFLAG%"=="00" goto TRYAGAIN
if "%FVARFLAG%"=="01" goto FILE
if "%FVARFLAG%"=="10" goto DIR
if "%FVARFLAG%"=="11" goto TRYAGAIN
goto TRYAGAIN
:DIR
if exist %FVAR%\ (
echo Successfully set dir name!
goto END
)
goto TRYAGAIN
:FILE
if exist %FVAR% (
echo Successfully set file name!
goto END
)
goto TRYAGAIN
rem if /i "%option:"=%"=="Y" goto YES //This line left in for future use
rem if /i "%option:"=%"=="N" goto NO //This line left in for future use
goto END
::-------------------------------------------------------
:: TRYAGAIN - Returns user to input menu on invalid entry
::-------------------------------------------------------
:TRYAGAIN
echo ------------------------------
echo Invalid selection...try again
echo ------------------------------
goto INPUT
:END
goto :EOF
I like this application! The use of arrays allows you to write simpler and more powerful code. This is my version:
#echo off
setlocal EnableDelayedExpansion
rem Select a file browsing a directory tree
rem Antonio Perez Ayala
set pageSize=30
rem Load current directory contents
:ProcessThisDir
for /F "delims==" %%a in ('set name[ 2^>NUL') do set "%%a="
set numNames=0
for /D %%a in (*) do (
set /A numNames+=1
set "name[!numNames!]=<DIR> %%a"
)
for %%a in (*.*) do (
set /A numNames+=1
set "name[!numNames!]= %%a"
)
rem Show directory contents, one page at a time
set start=1
:ShowPage
if %start% equ 1 (
set "less="
) else (
set "less=-=Previous page, "
)
set /A end=start+pageSize-1
if %end% gtr %numNames% (
set end=%numNames%
set "more="
) else (
set "more=+=Next page, "
)
cls
echo Directory: %CD%
echo/
for /L %%i in (%start%,1,%end%) do echo %%i- !name[%%i]!
echo/
:GetOption
set "option="
set /P "option=Enter desired item (%less%%more%Nothing=..): "
if not defined option (
cd ..
goto ProcessThisDir
) else if "%option%" equ "-" (
set /A start-=pageSize
if !start! lss 1 set start=1
goto ShowPage
) else if "%option%" equ "+" (
if defined more set /A start+=pageSize
goto ShowPage
) else if not defined name[%option%] (
goto GetOption
) else if "!name[%option%]:~0,5!" equ "<DIR>" (
cd "!name[%option%]:~8!"
goto ProcessThisDir
)
rem Return selected file
cls
for %%a in ("!name[%option%]:~8!") do set "result=%%~Fa"
echo Result="%result%"

Findstr doesn't accept variable CMD

The purpose is to scan a given folder for media files and send the mediainfo to info.txt BUT also to give user an option to scan only for files having a particular text string.
My bat file:
#echo off
setLocal EnableDelayedExpansion
echo. >info.txt
set /P "folder=Enter folder path: "
set /P "_input=Search all files (y/n): "
if /I "%_input%" == "y" (
dir %folder% /B /O:N | findstr /I ".wmv$ .mpg$ .mkv$ .mpeg$ .mp4$ .avi$" >filename.txt
for /f "tokens=* delims= " %%a in ('type filename.txt') do (
set _in=%_in%%%a
mediainfo --Inform=file://template.txt "%folder%!_in!" >>info.txt
echo. >>info.txt
)
) else (
set /P "_str=Enter file string: "
dir %folder% /B /O:N | findstr /I "%_str%" >filename.txt
for /f "tokens=* delims= " %%a in ('type filename.txt') do (
set in=%in%%%a
mediainfo --Inform=file://template.txt "%folder%!in!" >>info.txt
echo. >>info.txt
)
)
del filename.txt
cls
pause
Though the first part of if loop works correctly but the 'else' part don't, I can't get the error because with a flicker of an eye it disappears & I can't troubleshoot it
Well you could troubleshoot if you left ECHO ON and removed the CLS or put the pause before CLS.
Your ELSE block is failing because you are setting _str within the block and then attempting to use the value via normal expansion. You need to use delayed expansion.
Even your first IF block looks wrong because your SET statement is using normal expansion. The end result is each iteration is simply passing the current filename to mediainfo, which actually makes sense. It looks to me like you don't even need the _in variable in either block.
Your code is way more complicated than need be: I believe the following will give the result you are looking for:
#echo off
setlocal
echo. >info.txt
set /P "folder=Enter folder path: "
set /P "_input=Search all files (y/n): "
if /i "_input" == "y" (
set "_mask=*.wmv *.mpg *.mkv *.mpeg *.mp4 *.avi"
) else (
set /P "_mask=Enter file string: "
)
if /i "_input" neq "y" set "_mask=*%_mask%*"
pushd "%folder%"
set "popped="
for %%F in (%_mask%) do (
if not defined popped popd
set popped=1
mediainfo --Inform=file://template.txt "%%F" >>info.txt
echo. >>info.txt
)
pause
I would take it one step further and expect the user to supply any wildcards in the file string. That would give the user more control, and would simplify the code a bit more.
#echo off
setlocal
echo. >info.txt
set /P "folder=Enter folder path: "
set /P "_input=Search all files (y/n): "
if /i "_input" == "y" (
set "_mask=*.wmv *.mpg *.mkv *.mpeg *.mp4 *.avi"
) else (
set /P "_mask=Enter file mask: "
)
pushd "%folder%"
set "popped="
for %%F in (%_mask%) do (
if not defined popped popd
set popped=1
mediainfo --Inform=file://template.txt "%%F" >>info.txt
echo. >>info.txt
)
pause

Resources