How to rename files in Windows CMD (command prompt) – Stack Overflow

.cmd script to find & replace text in multiple files

Programming newbie in a bit of a pickle here. I know next to nothing about .cmd or .bat files or the like, but I’m to understand that .cmd is the way to go for a little project I’m currently undertaking. Basically, I’m looking to distribute a file which, when executed, alters two very specific lines from two individual .ini files located in the same folder as the .cmd file.

For NewGame.ini, I would very much like for the following line to be changed from:

FullHealthLimit = 1000

…to…

FullHealthLimit = 9999

And for NewGameUI.ini, I’d like for the following line to be changed from:

m_PosOffset=(X=25,Y=-99)

…to…

m_PosOffset=(X=-9999,Y=-9999)

That’s it. I just need one executable file to perform two — hopefully — quite basic tasks. Reason being is that my friends and I are really into modding certain video games, but want to make it much easier to distribute files.

I’ll be honest: I’ve had so much trouble trying to implement solutions from other topics and make it work for my situation (largely because of the presence of an equals sign causing grief) that I’m beginning to wonder if it’s even possible. I’m at my wits’ end, I tells ya! 😉

If anyone could provide the necessary code for me, ready to be plonked into a text file and saved as a .cmd file or whatnot, then I would be eternally grateful. I just want for me and my little circle of chums to be able to distribute our little mods amongst our humble community.

Thank you so much for reading about and hopefully looking into my quandary! I really appreciate any and all help. Cheers!

Batch command to replace text in file

I know this question is asked many times, but I didn’t get the answer for what I am searching.
I want to replace a pattern using windows .bat file.

I know how to replace X with Y.

But I am trying to replace say installPath with C:ProgramfilesInstall.

Here, I am facing issues as the new value string contains i.e special character.

Please let me know how I can replace this.

Batch. replace few files in a folder with another file

First folder with path “D:Test1” have file “0.txt” inside.

Second folder with path “D:Test2” have files “1.txt”, “2.txt” and “3.txt” and etc.

I want replace all .txt files in second folder with 0.txt from first folder, but i want save old names.
When done, i want also mark all files inside second folder as “Read Only”. If possible…

Very appreciate any help. Thanks!

How to rename files in windows cmd (command prompt)

Renaming 1 file in cmd is very easy:
In this example we have a sample1.txt and we want to change its name to sample2.txt:

 in command prompt type: c:temp> ren sample1.txt sample2.txt [enter]

Let’s say the filename is sample1-some-unwanted-text-1234.txt and we want to change it to sample1.txt:

 in command prompt, type: c:temp> ren sample1-some-unwanted-text-1234.txt sample1.txt

Renaming 1 file by replacing multiple unwanted characters using a star:
Let’s say the filename is sample1-some-unwanted-text-1234.txt and we want to change it to sample1.txt without having to type the whole filename:

 in command prompt: c:temp> ren sample1*.txt sample1.txt

This * basically means any characters inbetween sample1 and .txt will be replaced.

:/>  Memtest86 – программа для проверки оперативной памяти компьютера, как протестировать ОЗУ и пользоваться memory test, инструкция

Renaming multiple files with similar names
If you want to rename multiple files, i.e. sample1 2020-08-01.txt, sample2 2020-08-05.txt, sample3 2020-08-10.txt,sample4 2020-08-13.txt, you want to keep the first 7 characters you want to get rid of the dates:

 in command prompt: c:temp> ren sample?*.txt sample?.txt

In this example, you want to keep the word sample and the number X (where X can be any number or character). Using a ? will leave the number in place and * instructs the rename-command to replace any characters in between sampleX and .txt

Warning: It happens very quickly that a command prompt rename operation renames too many files and you can’t undo it. So, when renaming multiple files it is advisable to make a copy of all the files you want to rename, put them in a temp folder, then run your rename commands in the temp folder, and when you’re certain that it works, go back and rename the original files.

How to replace string inside a bat file with command line parameter string

First of all, you’ll have to store %1 into a variable, then you will be able to perform the replacements.

Basically, the syntax for the replacement is this:

%variable:str1=str2%

which means: ‘replace every str1 in variable with str2.

In your case both str1 and str2 are parameters, not literal strings. Using the above template directly you might end up with this expression:

%variable:%3=%4%.

But that would confuse the parser, as it wouldn’t know that %3 and %4 should be evaluated first. In fact, it would first try to evaluate %variable:% (and fail).

One of the solutions in this case could be to use a method called ‘lazy’ delayed evaluation. Basically, you are passing the command where you are evaluating a variable, to the CALL command. The transformation of the original command to its ‘CALL version’ is like so:

ECHO %var% ==> CALL ECHO %%var%%.

Note the double %s. At parse time they are evaluated to single %s. The resulting command would be parsed again by CALL, and the ultimate effect would be the same as in case of the original command, ECHO %var%.

So it works the same as the original command (which is good), and what we are gaining here is the later time of evaluation, I mean the final evaluation, when the variable is actually replaced with its value. Knowing about that effect, we can construct our expression in such a way that %3 and %4 are evaluated first, and then the entire resulting expression. Specifically, like this:

%%variable:%3=%4%%

After the first parse this expression would become something like this:

%variable:x=y%

That would be parsed again, and the output would be variable‘s modified contents.

:/>  CHCP – просмотр или изменение кодовой страницы.

For better illustration, here’s a simple working example:

SET "output=%1"
CALL SET output=%%output:%3=%4%%
ECHO %output%

UPDATE

There’s another method of doing the same thing, which I should probably have mentioned first.

The Windows command shell supports a proper delayed expansion. It is simpler in use, but has some caveats.

First, how to use it. The syntax for delayed expansion is !var! instead of %var% for immediate expansion (which remains valid and can be used alongside with the delayed expansion syntax).

Probably !var! will not work in your script until you enable the syntax with the command:

SETLOCAL EnableDelayedExpansion

The ENDLOCAL command closes the block within which the delayed expansion syntax is valid and interpreted by the command shell.

The above example script could be rewritten like this:

SET "output=%1"
SETLOCAL EnableDelayedExpansion
SET output=!output:%3=%4!
ECHO !output!
ENDLOCAL

So how this works in case of the SET output=!output:%3=%4! command:

  • %3 and %4 are evaluated immediately, i.e. at the parse time – they are replaced with x and y respectively;

  • the command becomes this: SET output=!output:x=y!;

  • the command is about to execute – the ! expression is evaluated (xs are replaced with ys);

  • the command is executed – the output variable is modified.

Now about the caveats. The first thing to remember is that the ! becomes part of the syntax and is consumed and interpreted whenever encountered. So you’ll need to escape it where you want to use it as a literal (like ^!).

Another caveat is the primary effect of a SETLOCAL/ENDLOCAL block. The thing is, all the changes to environment variables within such a block are, well, local. Upon exiting the block (upon executing ENDLOCAL) the variable is set to the value it had prior to entering it (prior to executing SETLOCAL). This means for you that the changed value of output will only be valid within the SETLOCAL block which you had to initiate for using the delayed expansion in the first place. Possibly this may not be a problem in your particular case, if you just need to modify the value and then use it right away, but you should probably have to remember it for the future.

Note: As per jeb‘s comment, you can save the modified value and leave the SETLOCAL block using this trick:

ENDLOCAL & SET "output=%output%"

The & operator simply delimits the commands when they are placed on the same line. They are executed one after the other, in the same order they are specified. The thing is, by the moment of parsing the line, the SETLOCAL block hasn’t been left yet, so %output% evaluates to the modified value, which is still valid. But the assignment is actually executed afterENDLOCAL, i.e. after leaving the block. So you are effectively storing the modified value after leaving the block, thus preserving the changes. (Thanks, jeb!)

:/>  Как узнать ключ Windows XP, Vista, Windows 7, 8, 8.1, 10 в случае, если операционная система не загружается

More information:

  1. On delayed expansion:
  1. On substring replacement:

Python

This language is very versatile and is also used in a wide variety of applications. It has a lot of functions for working with strings, among which is replace(), so if you have variable like var=”Hello World” , you could do var.replace(“Hello”,”Good Morning”)

Simple way to read file and replace string in it would be as so:

python -c "import sys;lines=sys.stdin.read();print lines.replace('blue','azure')" < input.txt

With Python, however, you also need to output to new file , which you can also do from within the script itself. For instance, here’s a simple one:

#!/usr/bin/env python
import sys
import os
import tempfile
tmp=tempfile.mkstemp()
with open(sys.argv[1]) as fd1, open(tmp[1],'w') as fd2: for line in fd1: line = line.replace('blue','azure') fd2.write(line)
os.rename(tmp[1],sys.argv[1])

This script is to be called with input.txt as command-line argument. The exact command to run python script with command-line argument would be

 $ ./myscript.py input.txt
$ python ./myscript.py input.txt

Of course, make sure that ./myscript.py is in your current working directory and for the first way, ensure it is set executable with chmod x ./myscript.py

Python can also have regular expressions , in particular, there’s re module, which has re.sub() function, which can be used for more advanced replacements.

Remove spaces from a text string

To delete space characters use the same syntax as above:

SET _no_spaces=%_some_var: =%

Как через cmd заменить n-ую строку в текстовом файле?

Здравствуйте. Сабж. Надо заменить 13ю строку в файле на заранее известную. Пишу так

for /f “skip=12” in (settings.ini) do (echo dparm=BIND=0,lck=’ru’,APP=’GPS’,HST=’%COMPUTERNAME%’)

По задумке должно пропустить 12 строк с начала файла и заменить на то, что указано в скобках. По факту – ноль реакции. Возможно, надо еще прервать цикл, т.к. замена производится один раз, но не уверен, это предположение, раньше с смд дел не имел.