Saturday, April 6, 2013

Rename multiple files at once

rename with wildcards only works on files, to rename a directory, use move;
C:\Temp>echo "test" > olle12  
C:\Temp>mkdir olle13
C:\Temp>rename "*12" 12
C:\Temp>rename "*13" 13
The syntax of the command is incorrect.
C:\Temp>move "*13" 13
C:\Temp\olle13
    1 dir(s) moved.
C:\Temp>dir
 Directory of C:\Temp

2013-04-03  10:01                 9 12
2013-04-03  10:01    <DIR>          13 
 
Rename also works on folders properly:

ren "the god of high school 12" 12
.. or you use a for loop:
for /d %i in (*12) do ren "%~i" 12
 

Trim leading slashes using only a batch file

CMD (replace %m with %%m for running this in a batch file):

for /f "delims=\ tokens=*" %m in ('net view ^| findstr /r "^\\\\"') do (
  echo %m
) >out.txt
 
 
PowerShell:

net view | select-string '^\\\\' -AllMatches `
  | % { $_ -replace '^\\\\', '' } >out.txt

Delete all folders named XXX in folder YYY by DOS command

From the command line:

for /D %f in (XXX*) do rmdir %f /s
 
You can do this via the CMD line.

RD /S /Q "Full Path of Folder"
 

Running an executable from bash script

A bash script will always finish the script after completion of any called script or executable. example:
@echo off
echo hello
"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
echo hope you had fun browsing the web!
pause
This will always echo the last line of code as soon as firefox is closed.

How to check the status of call command in dos batch file

echo  1.Building all four project.
call apacheant\bin\ant -buildfile build-all.xml >logfile.txt
findstr "succeed" logfile.txt >nul
if errorlevel 1 (echo Build failed) else (echo Build Succeeded)
 
Naturally, the echo ... could be replaced by 'set antstatus=SUCCEED` if required.
Don't try to use ERRORLEVEL to control the processing since MANY commands will change ERRORLEVEL to report their own status.

It may also be possible that ANT returns a status on termination. You could check with
echo %errorlevel%
 
after the ant step. If it returns an errorlevel, then you don't need to create and interpret the logfile.
The IF ERRORLEVEL syntax is

if errorlevel n Command_if_errorlevel_is_n_OR_GREATER_THAN_n

How copy text between special characters in DOS Batch?

Here is the REPL.BAT script that enables the above to work. Full documentation is embedded within the script. It is surprisingly powerful and efficient - I have successfully used it to solve many search and replace batch scripting problems.
@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment

::************ Documentation ***********
:::
:::REPL  Search  Replace  [Options  [SourceVar]]
:::REPL  /?
:::
:::  Performs a global search and replace operation on each line of input from
:::  stdin and prints the result to stdout.
:::
:::  Each parameter may be optionally enclosed by double quotes. The double
:::  quotes are not considered part of the argument. The quotes are required
:::  if the parameter contains a batch token delimiter like space, tab, comma,
:::  semicolon. The quotes should also be used if the argument contains a
:::  batch special character like &, |, etc. so that the special character
:::  does not need to be escaped with ^.
:::
:::  If called with a single argument of /? then prints help documentation
:::  to stdout.
:::
:::  Search  - By default this is a case sensitive JScript (ECMA) regular
:::            expression expressed as a string.
:::
:::            JScript syntax documentation is available at
:::            http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
:::
:::  Replace - By default this is the string to be used as a replacement for
:::            each found search expression. Full support is provided for
:::            substituion patterns available to the JScript replace method.
:::            A $ literal can be escaped as $$. An empty replacement string
:::            must be represented as "".
:::
:::            Replace substitution pattern syntax is documented at
:::            http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
:::
:::  Options - An optional string of characters used to alter the behavior
:::            of REPL. The option characters are case insensitive, and may
:::            appear in any order.
:::
:::            I - Makes the search case-insensitive.
:::
:::            L - The Search is treated as a string literal instead of a
:::                regular expression. Also, all $ found in Replace are
:::                treated as $ literals.
:::
:::            E - Search and Replace represent the name of environment
:::                variables that contain the respective values. An undefined
:::                variable is treated as an empty string.
:::
:::            M - Multi-line mode. The entire contents of stdin is read and
:::                processed in one pass instead of line by line. ^ anchors
:::                the beginning of a line and $ anchors the end of a line.
:::
:::            X - Enables extended substitution pattern syntax with support
:::                for the following escape sequences:
:::
:::                \\     -  Backslash
:::                \b     -  Backspace
:::                \f     -  Formfeed
:::                \n     -  Newline
:::                \r     -  Carriage Return
:::                \t     -  Horizontal Tab
:::                \v     -  Vertical Tab
:::                \xnn   -  Ascii (Latin 1) character expressed as 2 hex digits
:::                \unnnn -  Unicode character expressed as 4 hex digits
:::
:::                Escape sequences are supported even when the L option is used.
:::
:::            S - The source is read from an environment variable instead of
:::                from stdin. The name of the source environment variable is
:::                specified in the next argument after the option string.
:::

::************ Batch portion ***********
@echo off
if .%2 equ . (
  if "%~1" equ "/?" (
    findstr "^:::" "%~f0" | cscript //E:JScript //nologo "%~f0" "^:::" ""
    exit /b 0
  ) else (
    call :err "Insufficient arguments"
    exit /b 1
  )
)
echo(%~3|findstr /i "[^SMILEX]" >nul && (
  call :err "Invalid option(s)"
  exit /b 1
)
cscript //E:JScript //nologo "%~f0" %*
exit /b 0

:err
>&2 echo ERROR: %~1. Use REPL /? to get help.
exit /b

************* JScript portion **********/
var env=WScript.CreateObject("WScript.Shell").Environment("Process");
var args=WScript.Arguments;
var search=args.Item(0);
var replace=args.Item(1);
var options="g";
if (args.length>2) {
  options+=args.Item(2).toLowerCase();
}
var multi=(options.indexOf("m")>=0);
var srcVar=(options.indexOf("s")>=0);
if (srcVar) {
  options=options.replace(/s/g,"");
}
if (options.indexOf("e")>=0) {
  options=options.replace(/e/g,"");
  search=env(search);
  replace=env(replace);
}
if (options.indexOf("l")>=0) {
  options=options.replace(/l/g,"");
  search=search.replace(/([.^$*+?()[{\\|])/g,"\\$1");
  replace=replace.replace(/\$/g,"$$$$");
}
if (options.indexOf("x")>=0) {
  options=options.replace(/x/g,"");
  replace=replace.replace(/\\\\/g,"\\B");
  replace=replace.replace(/\\b/g,"\b");
  replace=replace.replace(/\\f/g,"\f");
  replace=replace.replace(/\\n/g,"\n");
  replace=replace.replace(/\\r/g,"\r");
  replace=replace.replace(/\\t/g,"\t");
  replace=replace.replace(/\\v/g,"\v");
  replace=replace.replace(/\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}/g,
    function($0,$1,$2){
      return String.fromCharCode(parseInt("0x"+$0.substring(2)));
    }
  );
  replace=replace.replace(/\\B/g,"\\");
}
var search=new RegExp(search,options);

if (srcVar) {
  WScript.Stdout.Write(env(args.Item(3)).replace(search,replace));
} else {
  while (!WScript.StdIn.AtEndOfStream) {
    if (multi) {
      WScript.Stdout.Write(WScript.StdIn.ReadAll().replace(search,replace));
    } else {
      WScript.Stdout.WriteLine(WScript.StdIn.ReadLine().replace(search,replace));
    }
  }
}

Combine two files using dos “copy” func

@echo off
echo ContentID = > package.conf
for /f "delims=" %%i in (package.conf) do set line1=%%i
for /f "delims=" %%i in (CID.txt) do set line2=%%i
echo %line1%%line2%>package.conf
echo Klicensee = 0x2A6AFBCF43D1579F7D738741A13BD42E>> package.conf
echo DRMType = Free>> package.conf
echo ContentType = minis>> package.conf
echo PackageVersion = 01.00>> package.conf

Output file:
ContentID = UP4306-NPUZ00210_00-MADBLOCKERALPHA1
Klicensee = 0x2A6AFBCF43D1579F7D738741A13BD42E
DRMType = Free
ContentType = minis
PackageVersion = 01.00
 
With new line at eof but it can be there :)