how to rename files using command line - command-line

I want to rename 2 files "Data1.txt" to "Log1.rtf" and "Data2.txt" to "Log2.rtf"
I am currently using this code
#ECHO OFF
FOR %%I IN ("%~dp0*.txt") DO (
SET "ext=%%~xI"
SETLOCAL EnableDelayedExpansion
RENAME "%%I" "%%~nI!Log.rtf"
ENDLOCAL
)
But it give output "data1log.rtf" and "data2log.rtf"

of course:
RENAME "%%I" "%%~nI!Log.rtf"
But it give output data1log.rtf and data2log.rtf
btw. what do you try to achive with setlocal delayedexpansion and that single ! ?
EDIT: if you insist in doing it with for (because perhaps, you have many files to rename):
#echo off
setlocal enabledelayedexpansion
for %%i in (*.txt) do (
set file=%%i
set file=!file:Data=Log!
set file=!file:.txt=.rtf!
echo ren %%i !file!
)
the first set sets the variable file to the filename
the second one replaces Data with Log
the third one replaces .txt with .rtf
then rename original filename (%%i) to the changed filename (!file!)
(the echo is there to just show the command on screen instead of really renaming files. Good for testing. If you are sure, that the code does, what you want, just remove the echo)
the setlocal enabledelayedexpansion is needed to use a variable, that is changed inside a block (between ( and )) inside the same block. Therefore you have to use the variable as !var! instead of %var%
Note: of course this code could be improved, but as a beginner: keep it as simple (and readable) as possible. For example, this code will replace Data, but not data or DATA, it will not handle spaces in filenames, ...

It might work better if you used separate code to rename each of the files, or does that defeat the object?
this website shows how to rename a file using command line:
http://www.sevenforums.com/tutorials/56013-file-folder-rename-command-prompt.html

for %%a in ("%~dp0data*.txt"
) do for /f "delims=DdAaTt" %%b in ("%%~na"
) do echo ren "%%~fa" "log%%b.rtf"
It just iterates over the indicated list of files, and for each filename, uses the unnecesary characters as delimiters for an aditional for loop. That way only the number is left and used to rename the file.
Commands to rename are echoed to console. If output is correct, remove the echo command to rename the files.

User mv command to rename files in windows (Using CLI)
As mentioned in above answer, mv command can be used in windows as well to rename the filename. I tried rename and ren commands s suggested, but I was getting error: bash: ren: command not found.
Use below to change the filename:
mv filename new_filename

Related

How to take output of dir search and modify specified file

I'm trying to use this script to assist technicians with renaming files that are found on an end users computer within their %appdata% folder. The script works up until this point, but I can't figure out how to take the output of the DIR search to use it as the current directory so I can modify the destination folder.
Basically, I need to make changes to this folder:
C:\users\bob\appdata\local\apps\2.0\'7'\'7'\time...exe_bfe88f94fc69adaa_0005.0011_none_b883acbb6e8d0075
The two 7's or wildcards are always different folder directory names, so that's why I can't use a static path to make changes to these folders. Anyways, here is the script so far, it works just fine in locating the folder I need, but I cannot seem to use the output to specify it as the target so I can make changes to it. Thank you for your help.
cd %appdata%
cd ..
cd local\apps\2.0
dir "time...exe_bfe88f94fc69adaa_0005.0011_none_39f58db4ac6311ec" /ad /s
I've tried using the pipeline argument (|) and the '&' and then using a rename command or a removedir, but it cannot find the file specified.
Thank you for your help!
Here's a batch-file which is a little more direct than just recursing the entire tree. It only steps over the two 'unknown' directory names, (%%~nxG\%%~nxH), and checks there for the named directory, (which you should edit as needed on line 3):
#Echo Off & SetLocal EnableExtensions
Set "DirName=time...exe_bfe88f94fc69adaa_0005.0011_none_39f58db4ac6311ec"
Set "BaseDir=%LocalAppData%\apps\2.0"
Set "AppPath="
For /D %%G In ("%BaseDir%\*")Do For /D %%H In ("%%G\*")Do For %%I In (
"%%H\%DirName%")Do If "%%~aI" GEq "d" Set "AppPath=%%~I"
If Not Defined AppPath Echo %DirName% Not Found & Pause & Exit /B 1
Echo %%AppPath%% = %AppPath% & Pause
Nothing else should be modified except for the last line which I added just to provide some output, (you/your technicians would use "%AppPath%" to reference the target directory from that point forward).
If you were looking for something in powershell, then perhaps this will push you in the right direction:
$DirName = "time...exe_bfe88f94fc69adaa_0005.0011_none_39f58db4ac6311ec"
$AppPath = (RvPa "$Env:LocalAppData\apps\2.0\*\*\$DirName").Path
$AppPath
Once again the last line is just to provide output and show you the variable you'll need to reference your target directory, and the first line will need editing as needed.
This code uses a FOR loop to find directory names that match. There is an ECHO inside the loop since I do not know if multiple directories could be found.
#ECHO OFF
CD "%APPDATA%\.."
FOR /F "delims=" %%A IN ('DIR /S /B /A:D "time...exe_bfe88f94fc69adaa_0005.0011_none_39f58db4ac6311ec"') DO (
ECHO Found directory "%%~A"
SET THEDIR=%%~A
)
DIR "%THEDIR%"
REN "%THEDIR%\file1.txt" "file2.txt"

Powershell in Batch file: Errors and Commands not executing

Below you can find the content of the two example text files I will use, example1.txt and obf_example1.txt. The latter one contains the string of example1.txt at the end of the file but has some obfuscated strings before.
example1.txt:
adasdkasdaksdasdkjlasdjasndjasd.
obf_example1.txt:
ŠxpÃÒ²Ø-Gêÿ ój"f>ïí H€À(ø4$/+#6Ni9Pvü¶ |CF CÀ¾ý~ª-°à9ÉOÿ V[o¦.E…-Š ƒ9Ú\žê*D´ß()^“£¹ìÅjXÑÍ¥â(¨µ×d'«P|I*èSººº&)Ø|̉ òÔ®¥Ô$LÁ:9ŠLá{¶nZÒبNÙÀØŒ‹0õ´Sék›áÇÉîÆbËF§BЄƒöZKaÒR ²°ÅšDn?+¶()IªP›$ÇEv©¡k€[ßè¨×q-Ëk!µTóPA²—: A ?ÉEEEGÐJúÌ©ÒWµHB¡aäXû|ÓË BPÁwr„Ûi¥åܺÈQ÷ORàSb,Šv¢D ,Žb’(2 öb¢wtKzíĦ#ï¯u©²Ù aîR隬ëÌTbà÷¥3ÄtSGì´R$)X Šù
'¹¨D³ÞeOK3!{·‹¦cäиNÅô:Na1žAÇ1ø8 &Fuôë %¸T¯_òMå†C"ý¤F ™º„Iµºí4Ü¡ˆc!ì•+3 ‰‹M K#JÁ«8¢bsL†!Ù“à­šn·öMå•Œ&ýèvÀ}¨?¦hùÊò(É#Žf~5‰‘qØçþƒ‰Å²ÓÖÊJU•âNWÁ«L¼Y”$G¢ßè&§ÖÉØŒS‘WàË„°SØW Ð¨´_è%‚Å¢ø.ãÃð”#X^þ*1þ‚q85¡lÒ‚Ò>‘¸ÿ £ôQôz#ø¤ÎõÚªï|Xö%;åÍËûGú+îUƒö³‰›p U±Ò ðtÜGÜÿ  ð,åXÿ k8È I”ÿ “½¿Ð`¨u5=SÓqyFÈ É8ôã¨ð£è6’H#lÄI10‚Ö§ÑdµÖ?t¡]D†9Zj,¥EɺÜEq¤#,ìn—¢º‚´€bc·ú¨Lû£ÿ Ó×ÿÙ||adasdkasdaksdasdkjlasdjasndjasd.
When I ran the following powershell command for example.txt in a batch file, it works and I get the output of example.txt:
#echo off
for /f "delims=" %%a in ('powershell Get-Content .\example.txt') do set _output=%%a
echo %_output%
adasdkasdaksdasdkjlasdjasndjasd
Good so far.
However, when I ran the above powershell command for obf_example1.txt, it does not work and I get the following error message:
'¹¨D³ÃzeOK3!{·â?¹Â¦cäÃ?Â?¸Â?NÃ.ô:Na1žAÃ╬1ø8
The command "FuôëÂ" is either misspelled or could not be found.
The command "ýèvÃ?}¨?¦hùÃSÂ?ò" is either misspelled or could not be found.
Why? Never mind I thought: As I am only interested in the last n characters both in example1.txt and obf_example1.txt accordingly, my idea was to extract the last n characters and check if I can see the output of obf_example1.txt then. To check if my idea works, I run the following command for example1.txt to get the last 4 characters as an example:
#echo off
for /f "delims=" %%a in ('powershell $a=Get-Content .\example.txt; $a.substring^(0,$a.length-4^)') do set _output=%%a
echo.%_output%
It doesn't show me anything though. %_output% seems to be empty. How to fix that? And will the fixed version work for obf_example1.txt as well so that I get an output there instead of the above error message?
Apparently, the piece of text you are after is behind the ||.
With PowerShell you can easily get that by using
((Get-Content 'D:\Test\obf_example1.txt' -Raw) -split '\|\|')[-1]
Returns
adasdkasdaksdasdkjlasdjasndjasd
Isn't htis what you want?
You could try reading the last 4 bytes, if you really are taking text characters from what is clearly not a text file. (My guess is that it is text hidden inside a binary file, probably a graphic file).
#For /F Delims^=^ EOL^= %%G In (
'%__AppDir__%WindowsPowerShell\v1.0\powershell.exe -NoP^
"$f=[IO.File]::OpenRead('C:\Users\Ferit\Desktop\obf_example1.txt');"^
"$f.Seek(-4,[System.IO.SeekOrigin]::End)|Out-Null;$buffer=new-object Byte[] 4;"^
"$f.Read($buffer,0,4)|Out-Null;$f.Close();"^
"[System.Text.Encoding]::UTF8.GetString($buffer)"')Do #Set "_output=%%G"
#Set _output 2>NUL&&Pause
Don't forget to modify the text file path, (on line 3), and the three instances of 4 if you want more or less bytes. The last line is included just to show you the output, (you would obviously replace that with your own code).
The following works for me to get the "clear-text" part after || (from your example):
for /f "delims=" %%a in (.\obf_example1.txt) do set "_output=%%a"
set _output
echo testing last 10: %_output:~-10%
set "_output=%_output:*||=%"
set _output
echo %_output%
(it might not work with different encodings of the text file)
(Consider Powershell - cmd has a limit on line length and can easily be overwhelmed)

Remove Carriage Return from String Field in File Windows Command Line

I have a file that is ouput with | as the delimiter. However, one of the fields is a description field from the source system which contains carriage returns. This is an issue when trying to read the file as it breaks it on to a new line. What I would like to do is remove all CF/LF that aren't preceeded by a |.
I feel like this should be possible on command line but haven't been able to come up with it.
Sample data
|A|Testing CF/LF
This|CF/LF
Expected Output
|A|Testing This|CF/LF
#ECHO Off
SETLOCAL
SET "line="
(
FOR /f "delims=" %%a IN (q26895698.txt) DO (
CALL :generate "%%a"
)
)>newfile.txt
TYPE newfile.txt
GOTO :EOF
:generate
SET "line=%line%%~1"
IF "%line:~-1%"=="|" SET "line="&FOR %%x IN ("%line%") DO ECHO(%%~x
GOTO :eof
I used a file named q26895698.txt containing your data (such as it was) for my testing.
Produces newfile.txt
Can't help but get the impression that you'd be better off with SED thouh - google "GNU SED" for details...

MS DOS edit a file

I am writing a batch script which I wish to open a file and then change the second line of it. I want to find the string "cat" and replace it with a value that I have SET i.e. %var% . I only want this to happen on the second line (or for the first 3 times). How would you go about doing this?
I just solve it myself. It will lookup var on line two only.
#echo OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET filename=%1
set LINENO=0
for /F "delims=" %%l in (%filename%) do (
SET /A LINENO=!LINENO!+1
IF "!LINENO!"=="2" ( call echo %%l ) ELSE ( echo %%l )
)
But I prefer using cscript (vbscript or even jscript).
First of all, using a batch file to achieve this, is messy (IMHO). You will have to use an external tool anyway to do the string replacement. I'd use some scripting language instead.
If you really want to use a batch, this will get you started.
This would be ugly to do with native batch scripting. I would either
Do this in VBScript. If you really need this in a batch file, you can call the VBScript file from the batch script. You can even pass in %var% as an argument to the VBScript.
Use a sed script. There are windows ports of Unix commands like GnuWin32, GNU Utilities for Win32 (I use these), or Cygwin.
I would create a script that would:
scan the input file
write to a second output file
delete the input
rename the output
As far as the dos commands to parse, I did a Google Search and came up with a good starting point:
#echo off
setlocal enabledelayedexpansion
set file=c:\file.txt
set output=output.txt
set maxlines=5000
set count=0
for /F "tokens=* usebackq" %%G in ("%file%") do (
if !count!==%maxlines% goto :eof
set line=%%G
set line=!line:*000000000000=--FOUND--!
if "!line:~0,9!"=="--FOUND--" (
echo %%G>>"%output%"
set /a count+=1
)
)
(Stolen from teh Intarwebnet)

Search and replace with a batch file

I am writing a batch file script using Windows command and want to change each occurrence of some blank space with "," What is the simplest way to do that?
If your users are a list of words on one line in a text file, separated by spaces, eg:
one two three four
Create a batch file SpaceToComma.bat as follows:
#echo off
setlocal
for /F "tokens=* delims= " %%a in (%1) do #set data=%%a
echo %data: =,%
endlocal
Then run it, you'll get the words separated by commas. Is this what you want?
C:\>SpaceToComma.bat data.txt
one,two,three,four
If you have a multi-line file, then this will do it:
data.txt
one two three four
five six seven
SpaceToComma.bat
#echo off
setlocal
for /F "tokens=* delims= " %%a in (%1) do #call :processaline %%a
endlocal
goto :eof
:processaline
setlocal
set data=%*
echo %data: =,%
endlocal
goto:eof
Output
C:\>SpaceToComma.bat data.txt
one,two,three,four
five,six,seven
(There's probably a clever way of doing this without the subroutine, using the !data! syntax for delayed variable expansion, but I couldn't get it to work with the substitution syntax.)
If this is not what you want, then please explain and I can try to help.
(PS: I delight in using batch files where people insist it can't be done.)
You could download sed.exe from http://unxutils.sourceforge.net/ and run this command:
sed -e "s/ /,/" infile.txt >outfile.txt
Well it will depend a lot on how you are getting the data, but you may be able to finagle something with a For-Do construct. Make the field seperator be a space then build the string back in the do with a , between each token. Might I suggest a more robust scripting language? You should have VBScript on just about any relatively modern windows bow.