How to remove a single character from the filename of a list of files in a folder using DOS command? - dos

I have a list of files like these:
icone1.gif
icone2.gif
icone1.gif
icone11.gif
icone12.gif
icone13.gif
icone14.gif
icone15.gif
I want to remove 'e' from it so they will icon1.gif, icon2.gif and so on...
I tried this from the DOS Command Prompt:
ren icone*.gif icon*.gif
Didn't work.

Create a batch file in the folder by typing "notepad go.bat" at the command prompt and hitting enter and drop this in then save and exit notepad:
for %%i in ("*.gif") do (set fname=%%i) & call :rename
goto :eof
:rename
::Cuts off 1st five chars, then appends Icon and the remaining chars
ren "%fname%" "Icon%fname:~5%"
goto :eof
Double click the batch file in windows or from the command prompt type go and press enter

See How does the Windows RENAME (REN) command interpret wildcards? for rules that can explain why your command does not work.
Assuming all your file names have a digit after "icone" (really only care that you never have another "e" following "icone"), then the following one liner will work from the command line.
for /f "tokens=1* delims=eE" %A in ('dir /b icone*.gif') do #ren "%Ae%B" "%A%B"
Double up the percents if you put the command within a batch script.
For a really simple and robust solution, use my JREN.BAT regular expression renaming utility, pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward.
jren "^(icon)e(.*\.jpg)" "$1$2" /i

Related

findstr not working as expected

I am trying to find last line in a text file using the regex ^.*\z, it's working fine in notepad++ but when I try it in cmd using findstr /R "^.*^Z" file.txt not working.
Open a command prompt window and run findstr /?. The output help explains what FINDSTR supports. The regular expression feature is limited in FINDSTR. It does not support all the features as supported by Boost Perl Regular Expression library used by many text editors in various versions.
This batch code could be used to get last non empty line from a file assigned to an environment variable:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LastLine="
if exist "file.txt" for /F "usebackq eol= delims=" %%# in ("file.txt") do set "LastLine=%%#"
echo Last line is: "%LastLine%"
endlocal
Command FOR skips all empty lines and by default also all lines starting with a semicolon. For that reason eol= is used to define form-feed control character as end of line. In case of last line of file surely never starts with ; it would be best to remove eol= from the FOR command line.
In case of file to process always has at least X lines, it would make sense to add to the FOR options after usebackq the option skip=X to skip the first X lines of the file for faster processing.
For details on command FOR open a command prompt window and run for /?.

Why does FOR loop command not work in a batch file which works on Windows command prompt?

FOR /L %A IN (1,1,100) DO echo %A
The code above in a batch script results in this error:
A was unexpected at this time.
The same command line works fine on Windows command prompt.
What is the problem?
You need to use double percent characters:
FOR /L %%A IN (1,1,100) DO echo %%A
If you run FOR /? you'll find that the first paragraph after the parameter list starts as follows:
To use the FOR command in a batch program, specify %%variable instead
of %variable.
As an example, let's start with a simple FOR loop:
FOR %x in (*) DO ECHO %x
This will run just fine from a command prompt, printing out the name of each file in the current directory, but if we use this verbatim in a Batch file, we'll get an error saying this:
x was unexpected at this time.
This is because Batch files have some extra abilities that use the percent sign immediately followed by some text, so when FOR is called from inside a Batch file it instead looks for two percent signs. So if we want to use that same FOR loop in a Batch script, we need to replace each instance of %x with %%x.
What we end up putting in our Batch file is this:
FOR %%x in (*) DO ECHO %%x
The problem is with %, %A is for use on command lines only.
when used in batch files %A should be substituted with %%A.

Running a non bat extension file as a batch file

Let's say I have a text file, it contains batch commands. How can I run that text file as a batch file from within one, without renaming it. I want too keep a portable aspect too it, so no registry keys or such.
The reason for no renaming is too prevent leftover unrenamed files upon unexpected closure.
The simplest way is this:
cmd < file.txt
As in the previous answers, there are several commands that will not work in this file, like GOTO, SETLOCAL and others. However, multiline nested if and for commands do work as long as for replaceable parameters use just one percent (like in the command-line).
Although this method alaways show in the screen the executed commands (#echo off not works here), you may redirect the output to NUL and in the "Batch" file redirect the desired output to CON. For example, this is test.txt:
#echo off
echo Hello World! > CON
(for /L %a in (1,1,10) do (
echo Turn: %a
if %a equ 4 echo TURN NUMBER FOUR!
)) > CON
Output example:
C:\> cmd < test.txt > NUL
Hello World!
Turn: 1
Turn: 2
Turn: 3
Turn: 4
TURN NUMBER FOUR!
Turn: 5
Turn: 6
Turn: 7
Turn: 8
Turn: 9
Turn: 10
type some.txt>temp.bat
call temp.bat
del /q /f temp.bat
Is creating a temp file cheating?It's not mentioned as restriction in the question.Though you can loose the %ERRORLEVEL% because of the del command , but you can keep it in temp variable:
type some.txt>temp.bat
call temp.bat
set temp_el=%errorlevel%
del /q /f temp.bat
exit /b %temp_el%
I'm pretty sure you cannot do what you want. Windows will not let you configure the OS to recognize any other extensions as batch files. Only .bat and .cmd are supported.
You could process a series of simple commands within a text file using a FOR /F loop, but it will be very restrictive. For example, it will not support IF, FOR, GOTO Label, or CALL :Label. There are probably other restrictions. Within your main batch file, you could have the following:
for /f delims^=^ eol^= %%A in (script.txt) do %%A
You might be able to support IF and/or FOR if you execute the command via a new CMD.EXE shell, but then you cannot preserve the value of variables that might be SET by the command.
for /f delims^=^ eol^= %%A in (script.txt) do cmd /c "%%A"
See the windows shell commands
assoc. Associates a filename extension (e.g. *.txt) with a file type.
ftype. Lets you create a new file type that tells the windows shell how to open a particular kind of file.
From a command prompt, typing assoc /? or ftype /? will get you help on them. Or use your google-fu to find the MS docs.
*.bat is mapped to the file type batfile; *.cmd is mapped to the file type cmdfile. In windows 7 they are identical. If you want to be able to run files named *.foobar as a batch files, just type:
assoc .foobar=cmdfile
Then, assuming a file named 'sillyness.foobar' existing on the path, you just just type
c:\> sillyness
and it will find sillyness.foobar and execute it as a batch file. The Windows shell has a priority for how it resolves conflicts when you have files with the same name and different extensions (.com vs .cmd vs .bat, etc.)
Something like
assoc .pl=perlscript
ftype perlscript=perl.exe %1 %*
will set you up to run perl scripts as if they were .bat files.
If your batch commands are simple sequential ones then you could use this at the command prompt. Double the % signs for use in a batch file.
for /f "delims=" %a in (file.txt) do %a

Delete a Batch file variable in a text file

I am currently trying to delete a variable from a batch file which is in a text file
e.g. delete %variable%
where %variable% = "test"
So the batch script would delete the instance of "test" in the specified text file
Can this be done?
#echo off
setlocal enabledelayedexpansion
set variable=test
for /f "delims=" %%l in (foo.txt) do (
set "line=%%f"
echo !line:%variable%=!
)
To avoid potential special character issues with the string you are searching for, it may be better to just call findstr directly like this:
type input.txt | findstr /b /e /v "remove_line" > input_without_remove_line.txt
/b and /e together will only match if the "remove_line" is the only text on a line. /v will switch the output to only print all lines that do not match.
If you are sure you're not passing special characters, it is pretty easy to wrap that in a small batch and replace remove line with %1 or %* to use your passed parameters.
Unfortunately, you will need to use a temporary file - replacing the file in place doesn't work with the DOS output redirection.
If you were wanting to delete all instances of a specified word within any line, batch and findstr are probably not the way to do it. Look at sed, which can do much more and is freely available. If you can't install another utility, even vbscript using cscript would be a better way to do this than batch.

Detecting how a batch file was executed

Assuming Windows, is there a way I can detect from within a batch file if it was launched from an open command prompt or by double-clicking? I'd like to add a pause to the end of the batch process if and only if it was double clicked, so that the window doesn't just disappear along with any useful output it may have produced.
Any clever ways to do this? I'm looking for solutions I could rely on to work on a machine that was configured more or less with default settings.
I just ran a quick test and noticed the following, which may help you:
When run from an open command prompt, the %0 variable does not have double quotes around the path. If the script resides in the current directory, the path isn't even given, just the batch file name.
When run from explorer, the %0 variable is always enclosed in double quotes and includes the full path to the batch file.
This script will not pause if run from the command console, but will if double-clicked in Explorer:
#echo off
setlocal enableextensions
set SCRIPT=%0
set DQUOTE="
#echo do something...
#echo %SCRIPT:~0,1% | findstr /l %DQUOTE% > NUL
if %ERRORLEVEL% EQU 0 set PAUSE_ON_CLOSE=1
:EXIT
if defined PAUSE_ON_CLOSE pause
EDIT:
There was also some weird behavior when running from Explorer that I can't explain. Originally, rather than
#echo %SCRIPT:~0,1% | findstr /l %DQUOTE% > NUL
if %ERRORLEVEL% EQU 0 set PAUSE_ON_CLOSE=1
I tried using just an if:
if %SCRIPT:0,1% == ^" set PAUSE_ON_CLOSE=1
This would work when running from an open command prompt, but when run from Explorer it would complain that the if statement wasn't correct.
Yes. Patrick Cuff's final example almost worked, but you need to add one extra escape, '^', to make it work in all cases. This works great for me:
set zero=%0
if [^%zero:~0,1%] == [^"] pause
However, if the name of the batch file contains a space, it'll be double quoted in either case, so this solution won't work.
Don't overlook the solution of having two batch files:
abatfile.bat and abatfile-with-pause.bat
The second simply calling the first and adding a pause
Here's what I use :
rem if double clicked it will pause
for /f "tokens=2" %%# in ("%cmdcmdline%") do if /i "%%#" equ "/c" pause
I use a parameter "automode" when I run my batch files from scripts.
set automode=%7
(Here automode is the seventh parameter given.)
Some code follows and when the file should pause, I do this:
if #%automode%==# pause
One easy way to do it is described here:
http://steve-jansen.github.io/guides/windows-batch-scripting/part-10-advanced-tricks.html
There is little typo in the code mentioned in the link. Here is correct code:
#ECHO OFF
SET interactive=0
ECHO %CMDCMDLINE% | FINDSTR /L /I %COMSPEC% >NUL 2>&1
IF %ERRORLEVEL%==0 SET interactive=1
ECHO do work
IF "%interactive%"==1 PAUSE
EXIT /B 0
Similar to a second batch file you could also pause if a certain parameter is not given (called via clicking).
This would mean only one batch file but having to specify a -nopause parameter or something like that when calling from the console.
crazy idea: use tasklist and parse it's results.
I've wrote in a test batch file:
tasklist > test.out
and when I double-clicked it, there was an additional "cmd.exe" process just before the tasklist process, that wasn't there when the script was run from command line (but note that might not be enough if someone opens a command line shell and then double-click the batch file)
Just add pause regardless of how it was opened? If it was opened from command prompt no harm done apart from a harmless pause. (Not a solution but just thinking whether a pause would be so harmful / annoying )

Resources