Mostly Linux & Python syntax notes and hyperlinks.

Thursday, December 4, 2014

Windows Batch Script: substring to generate output name from input name without extension

If you want your batch script to create an output file name from an input file name by removing its 3-character extension, then you can use the batch substring method.
The substring syntax :~ is inserted between the opening and closing % signs that surround your variable.

Thus, instead of %complete_variable_name%,you have
%complete_variable_name:~[chars-to-skip],[chars-to-collect]%
  •  if [chars-to-skip] is negative, then it starts from the end of the string
  •  if [chars-to-collect] is negative, then it ends that many characters from the end of the string
e.g.
C:> set filename=abcde.txt 
C:> echo %filename% 
abcde.txt 
C:> echo %filename:~0,-3% 
abcde. 
C:> echo %filename:~-3,3% 
txt 
C:> set outname=%filename:~0,-4%.output 
C:> echo %outname% 
abcde.output

Windows Batch Script: Collecting Y/N inside FOR loop via subroutine

In Windows scripting, any variable such as %yn% is expanded before a FOR loop is activated.

To collect data inside a FOR loop you need to do two things:
  1. Use ! ! around your variable instead of % %
  2. At the top of the file: setlocal enabledelayedexpansion 
REM next line needed for !yn! to work: 
setlocal enabledelayedexpansion  

@echo off 
FOR %%G IN (a,b) DO (
    echo how about %%G? 
    call :YorN
    if !yn!==Y ( 
        echo yes
        call :eab %%G 
    ) else (echo no) 

pause 
goto:EOF 

:YorN
    echo Y or N
    set /P yn=Y/N:
    IF /I %yn%==y(
        set yn=Y
    ) ELSE (
        set yn=N
    )
    echo YorN %yn%
    goto:EOF
:EOF 

References:

http://stackoverflow.com/questions/2514476/the-value-returned-from-a-function-in-a-windows-batch-script-is-ignored-in-a-for
http://stackoverflow.com/questions/12021033/how-do-i-ask-a-for-user-input-and-receive-user-input-in-a-bat-and-use-it-to-run
http://ss64.com/nt/if.html