.Bat file to copy txt files without changing extension? - windows

I need to copy all .TXT files under a directory [subfolders included] and copy them to another directory [without subfolders] but I can't change the extension of the files after I copy them, for example to .OLD or .TXT.OLD. Is that possible to do it via .bat file? Is there any special tool to use instead?

Consider using powershell instead:
Get-ChildItem C:\path\to\root\dir -recurse | where {$_.extension -eq ".txt"} | % {Copy-Item $_.FullName -Destination C:\path\to\target\dir}

You just need to use the root part of the filename and then append your own extension in the rename. For example, to demonstrate that (you don't say you're having any issue with the logic of the actual process, just the extension manipulation, so that's what I'm addressing):
FOR %%I IN (*.txt) DO REN %%I %%~nI.txt.old
This will take all *.txt files in the current directory and rename them to the same root + extension .txt.old. There's a possible complication in that the resulting filename cannot already exist in a rename, so you may want to put it into a more complex loop such as:
FOR %%I IN (*.txt) DO (
[do other stuff here]
IF EXIST %%~nI.txt.old DEL %%~nI.txt.old
REN %%I %%~nI.txt.old
)
Try for /? at a command prompt and check out the last part of it for the syntax of filename/path substitution parameters

Related

Run ffmpeg on all files of a folder [duplicate]

I need to convert some xls files into xlsx files. I can successfully convert one xls file into xlsx by running this command into cmd prompt (windows):
ssconvert inputFileName.xls outputFileName.xlsx
(ssconvert is a Gnumeric's command-line utility that can convert between different spreadsheet file formats)
I'd like to write a batch file that FOR EACH file in a specified directory runs the command I wrote above, using the current file name both for input and for output filename.
For example, if I have this set of files:
c:\directory\file1.xls
c:\directory\file2.xls
c:\directory\file3.xls
the output should be
c:\directory\file1.xlsx
c:\directory\file2.xlsx
c:\directory\file3.xlsx
so the batch pseudo code should be something like
directory = c:\directory\
for (fileName in directory)
ssconvert fileName.xls fileName.xlsx
Can anyone help me?
for /r %%v in (*.xls) do ssconvert "%%v" "%%vx"
a couple have people have asked me to explain this, so:
Part 1: for /r %%v in (*.xls)
This part returns an array of files in the current directory that have the xls extension. The %% may look a little curious. This is basically the special % character from command line as used in %PATH% or %TEMP%. To use it in a batch file we need to escape it like so: %%PATH%% or %%TEMP%%. In this case we are simply escaping the temporary variable v, which will hold our array of filenames.
We are using the /r switch to search for files recursively, so any matching files in child folders will also be located.
Part 2: do ssconvert "%%v" "%%vx"
This second part is what will get executed once per matching filename, so if the following files were present in the current folder:
c:\temp\mySheet.xls,
c:\temp\mySheet_yesterday.xls,
c:\temp\mySheet_20160902.xls
the following commands would be executed:
ssconvert "c:\temp\mySheet.xls" "c:\temp\mySheet.xlsx"
ssconvert "c:\temp\mySheet_yesterday.xls" "c:\temp\mySheet_yesterday.xlsx"
ssconvert "c:\temp\mySheet_20160902.xls" "c:\temp\mySheet_20160902.xlsx"
Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES
in your case
forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert #file #fname.xlsx"
the only weird thing with this command is that forfiles automatically adds double quotes around #file and #fname. but it should work anyway
you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %% by % :
for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx
If you can run powershell it will be :
Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }
I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.
set codedirectory=C:\Users\code
for /r %codedirectory% %%i in (*.c) do
( some GCC commands )

How to Rename Bulk Files using CMD

I have a bunch of sql files that I would like to rename as they have the schema name at the start of the file like the following:
SCHEMA.TABLE.sql
Which I want to be renamed to:
TABLE.sql
Unfortunately as I am trying to do this on my work laptop, I can't download any third party software such Bulk Rename Utility so I am trying to do this using CMD.
What I attempted was the following:
REN SCHEMA.*.sql *.sql
which looks like it finds a match but nothing changes. So not sure what I need to change so would appreciate any advice as to where I am going wrong.
The ren command interprets the * in the target pattern *.sql so that it matches all source characters up to the last ., meaning that it matches the portion SCHEMA.TABLE of your sample. Therefore, the target name equals the source name.
Consult this great post on Super User: How does the Windows RENAME command interpret wildcards?
To remove the SCHEMA. part from your file names you need to use a for /F loop:
for /F "eol=| tokens=1* delims=." %I in ('dir /B /A:-D-H-S "*.*.sql"') do ren "%I.%J" "%J"
This fails in case there are more than one ., like in SCHEMA..TABLE.sql, for example.
Do not forget to double the %-signs when you want to use that code in a batch-file!
1.This can be done using powershell script pretty easily. Copy following script, edit $path to the path where the files are located.
$path = 'D:\MyFolder\My docs\testdelete'
$pathObject = get-childitem -path $path | where-object {$_.Psiscontainer -eq $false}
foreach($file in $pathObject)
{
$fileNameArray = $file.Name.Split(".")
Rename-Item -Path $file.FullName -NewName ($fileNameArray[1]+".sql")
}
2.Next save this script in a file named, say testrename.ps1. Open cmd change directory to the location where you saved testren.ps1 file and further run following command:
powershell -file "testren.ps1"
Here $path is the path where the files are located. $pathObject will get all the files in the said location. Further we iterate each file, split the name to get what comes after 'schema' and further rename it. If cmd is not a restriction then 1st script can also be directly run by opening powershell window on windows, copy paste the script after modifying the path and hit Enter key. In this case step 2 is not required.

Creating Bat file to execute a command on all files in folder and subfolders

I need to run this command line program on every xlsx file with a few parameters:
"C:\temp\cnv.exe" "param1" "param2" "param3", where
param1-complete path to *.xlsx file, also searched file(ex. "D:\temp\sample1.xlsx");
param2-complete path to output folder, should be the same for the current file(ex. "D:\temp\");
param3-static wording("-layout").
started from, but don't know how to finish:
cd "d:\temp\"
for /r %%i in (*.xlsx) do "C:\temp\cnv.exe" "%%i"........ "-layout"?
You do not need to do the cd with /R switch:
for /r "D:\Temp" %%i in (*.xlsx) do "C:\temp\cnv.exe" "%%i" "%%~dpi" -layout
Only the command with it's path c:\temp\cnv.exe and the paths should be double quoted (in case it contains whitespace) -layout and any other - switch does not require double quoting.
I see that you are not using it now, but when you are ready to use PowerShell, this might be a starting point.
Get-ChildItem -Recurse *.csv |
ForEach-Object { & C:\temp\exe `"$_.FullName1" `"$_.DirectoryName`" -layout }

Copy a file to all folders batch file?

I need copy credits.jpg from C:\Users\meotimdihia\Desktop\credits.jpg to D:\Software\destinationfolder and all subfolders
I read many and i write
/R "D:\Software\destinationfolder" %%I IN (.) DO COPY "C:\Users\meotimdihia\Desktop\credits.jpg" "%%I\credits.jpg"
then i save file saveall.bat but i run it , it dont work at all.
help me write 1 bat
Give this a try:
for /r "D:\Software\destinationfolder" %i in (.) do #copy "C:\Users\meotimdihia\Desktop\credits.jpg" "%i"
Of course, if it's to go into a batch file, double the '%'.
This was the first search I found on google for batch file copy file to all subfolders.
Here's a way with xcopy.
There's also robocopy but that would be too powerful for a simple task like this. (I've used that for entire drive backups because it can use multi-threading)
But, let us focus on xcopy.
This example is for saving to a file with the extension .bat. Just drop the additional % where there is two if running directly on the command line.
cd "D:\Software\destinationfolder"
for /r /d %%I in (*) do xcopy "C:\temp\file.ext" "%%~fsI" /H /K
cd "D:\Software\destinationfolder" change directory to the folder you want to copy the file to. Wrap this in quotes if the path has whitespaces.
the for loop - See help here. Or type for /? in a command prompt.
/r - Loop through files (recurse subfolders)
/d - Loop through several folders
%%I - %%parameter: A replaceable parameter
xcopy - Type xcopy /? in the command line for lots of help. You may need to press Enter to read the entire help on this.
C:\temp\file.ext - The file you want to copy
"%%~fsI" - Expands %%I to a full pathname with short names only
/H - Copies files with hidden and system file attributes. By default, xcopy does not copy hidden or system files
/K - Copies files and retains the read-only attribute on Destination files if present on the Source files. By default, xcopy removes the read-only attribute.
The last two parameters are just examples if you're having trouble with any read-only files and will retain the most important file properties.
Lots more xcopy parameters here
xcopy examples here
Just for completeness. This example below will copy the same file in each folder of the current directory and not any sub-folders. Just the /r option is removed for it to behave like this.
for /d %%I in (*) do xcopy "C:\temp\file.ext" "%%~fsI" /H /K
If you can use it: Here is a PowerShell solution (PowerShell is integrated in Windows 7 and available from XP and up):
$file = "C:\...\yourfile.txt"
$dir = "C:\...\YourFolder"
#Store in sub directories
dir $dir -recurse | % {copy $file -destination $_.FullName}
#Store in the directory
copy $file -destination $dir
I'm pretty sure that the last line can be integrated in dir ... but I'm not sure how (I do not use PowerShell very often).

How to copy a directory structure but only include certain files (using windows batch files)

As the title says, how can I recursively copy a directory structure but only include some files. E.g given the following directory structure:
folder1
folder2
folder3
data.zip
info.txt
abc.xyz
folder4
folder5
data.zip
somefile.exe
someotherfile.dll
The files data.zip and info.txt can appear everywhere in the directory structure. How can I copy the full directory structure, but only include files named data.zip and info.txt (all other files should be ignored)?
The resulting directory structure should look like this:
copy_of_folder1
folder2
folder3
data.zip
info.txt
folder4
folder5
data.zip
You don't mention if it has to be batch only, but if you can use ROBOCOPY, try this:
ROBOCOPY C:\Source C:\Destination data.zip info.txt /E
EDIT: Changed the /S parameter to /E to include empty folders.
An alternate solution that copies one file at a time and does not require ROBOCOPY:
#echo off
setlocal enabledelayedexpansion
set "SOURCE_DIR=C:\Source"
set "DEST_DIR=C:\Destination"
set FILENAMES_TO_COPY=data.zip info.txt
for /R "%SOURCE_DIR%" %%F IN (%FILENAMES_TO_COPY%) do (
if exist "%%F" (
set FILE_DIR=%%~dpF
set FILE_INTERMEDIATE_DIR=!FILE_DIR:%SOURCE_DIR%=!
xcopy /E /I /Y "%%F" "%DEST_DIR%!FILE_INTERMEDIATE_DIR!"
)
)
The outer for statement generates any possible path combination of subdirectory in SOURCE_DIR and name in FILENAMES_TO_COPY. For each existing file xcopy is invoked. FILE_INTERMEDIATE_DIR holds the file's subdirectory path within SOURCE_DIR which needs to be created in DEST_DIR.
try piping output of find (ie. the file path) into cpio
find . -type f -name '*.jpg' | cpio -p -d -v targetdir/
cpio checks timestamp on target files -- so its safe and fast.
remove -v for faster op, once you get used to it.
If Powershell is an option, you can do this:
Copy-Item c:\sourcePath d:\destinationPath -filter data.zip -recurse
The main disadvantage is it copies all folders, even if they will end up being empty because no files match the filter you specify. So you could end up with a tree full of empty folders, in addition to the few folders that have the files you want.
To copy all text files to G: and preserve directory structure:
xcopy *.txt /s G:
Thanks To Previous Answers. :)
This script named "r4k4copy.cmd":
#echo off
for %%p in (SOURCE_DIR DEST_DIR FILENAMES_TO_COPY) do set %%p=
cls
echo :: Copy Files Including Folder Tree
echo :: http://stackoverflow.com
rem /questions/472692/how-to-copy
rem -a-directory-structure-but-only
rem -include-certain-files-using-windows
echo :: ReScripted by r4k4
echo.
if "%1"=="" goto :NoParam
if "%2"=="" goto :NoParam
if "%3"=="" goto :NoParam
setlocal enabledelayedexpansion
set SOURCE_DIR=%1
set DEST_DIR=%2
set FILENAMES_TO_COPY=%3
for /R "%SOURCE_DIR%" %%F IN (%FILENAMES_TO_COPY%) do (
if exist "%%F" (
set FILE_DIR=%%~dpF
set FILE_INTERMEDIATE_DIR=!FILE_DIR:%SOURCE_DIR%=!
xcopy /E /I /Y "%%F" "%DEST_DIR%!FILE_INTERMEDIATE_DIR!"
)
)
goto :eof
:NoParam
echo.
echo Syntax: %0 [Source_DIR] [Dest_DIR] [FileName]
echo Eg. : %0 D:\Root E:\Root\Lev1\Lev2\Lev3 *.JPG
echo Means : Copy *.JPG from D:\Root to E:\Root\Lev1\Lev2\Lev3
It accepts variable of "Source", "Destination", and "FileName".
It also can only copying specified type of files or selective filenames.
Any improvement are welcome. :)
With find and cp only:
mkdir /tmp/targetdir
cd sourcedir
find . -type f -name '*.zip' -exec cp -p --parents {} /tmp/targetdir ";"
find . -type f -name '*.txt' -exec cp -p --parents {} /tmp/targetdir ";"
Similar to Paulius' solution, but the files you don't care about are not copied then deleted:
#echo OFF
:: Replace c:\temp with the directory where folder1 resides.
cd c:\temp
:: You can make this more generic by passing in args for the source and destination folders.
for /f "usebackq" %%I in (`dir /b /s /a:-d folder1`) do #echo %%~nxI | find /V "data.zip" | find /v "info.txt" >> exclude_list.txt
xcopy folder1 copy_of_folder1 /EXCLUDE:exclude_list.txt /E /I
That's only two simple commands, but I wouldn't recommend this, unless the files that you DON'T need to copy are small. That's because this will copy ALL files and then remove the files that are not needed in the copy.
xcopy /E /I folder1 copy_of_folder1
for /F "tokens=1 delims=" %i in ('dir /B /S /A:-D copy_of_files ^| find /V "info.txt" ^| find /V "data.zip"') do del /Q "%i"
Sure, the second command is kind of long, but it works!
Also, this approach doesn't require you to download and install any third party tools (Windows 2000+ BATCH has enough commands for this).
Under Linux and other UNIX systems, using the tar command would do this easily.
$ tar cvf /tmp/full-structure.tar *data.zip *info.txt
Then you'd cwd to the target and:
$ tar xvf /tmp/full-structure.tar
Of course you could pipe the output from the first tar into the 2nd, but seeing it work in steps is easier to understand and explain. I'm missing the necessary cd /to/new/path/ in the following command - I just don't recall how to do it now. Someone else can add it, hopefully.
$ tar cvf - *data.zip *info.txt | tar xvf -
Tar (gnutar) is available on Windows too, but I'd probably use the xcopy method myself on that platform.
For those using Altap Salamander (2 panels file manager) : in the Options of the Copy popup, just specify the file names or masks. Easy.
XCOPY /S folder1\data.zip copy_of_folder1
XCOPY /S folder1\info.txt copy_of_folder1
EDIT: If you want to preserve the empty folders (which, on rereading your post, you seem to) use /E instead of /S.
Using WinRAR command line interface, you can copy the file names and/or file types to an archive. Then you can extract that archive to whatever location you like. This preserves the original file structure.
I needed to add missing album picture files to my mobile phone without having to recopy the music itself. Fortunately the directory structure was the same on my computer and mobile!
I used:
rar a -r C:\Downloads\music.rar X:\music\Folder.jpg
C:\Downloads\music.rar = Archive to be created
X:\music\ = Folder containing music files
Folder.jpg = Filename I wanted to copy
This created an archive with all the Folder.jpg files in the proper subdirectories.
This technique can be used to copy file types as well. If the files all had different names, you could choose to extract all files to a single directory. Additional command line parameters can archive multiple file types.
More information in this very helpful link http://cects.com/using-the-winrar-command-line-tools-in-windows/
I am fine with regular expressions, lazy and averse to installs, so I created a batch file that creates the directory and copies with vanilla DOS commands. Seems laborious but quicker for me than working out robocopy.
Create your list of source files with complete paths, including drive letter if nec, in a text file.
Switch on regular expressions in your text editor.
Add double quotes round each line in case of spaces - search string (.*) replace string "\1", and click replace all
Create two lines per file - one to create the directory, one to copy the file (qqq will be replaced with destination path) - search string (.*) replace string md qqq\1\nxcopy \1 qqq\1\n and click replace all
Remove the filename from the destination paths – search \\([^\\^"]+)"\n replace \\"\n
Replace in the destination path (in this example A:\src and B:\dest). Turn OFF regular expressions, search qqq"A:\src\ replace B:\dest\ and click replace all.
md will create nested directories. copy would probably behave identically to xcopy in this example. You might want to add /Y to xcopy to suppress overwrite confirms. You end up with a batch file like so:
md "B:\dest\a\b\c\"
xcopy "C:\src\a\b\c\e.xyz" "B:\dest\a\b\c\e.xyz"
repeated for every file in your original list. Tested on Win7.
To do this with drag and drop use winzip there's a dir structure preserve option. Simply create a new .zip at the directory level which will be your root and drag files in.

Resources