Zip files with same name on Windows using batch script - windows

Let's say we have:
somedir
file1.eps
file1.jpg
file2.eps
file2.jpg
What I want to do is, to get zips of every eps, jpg couple with the same names like:
somedir
file1.zip
file2.zip
I can't figure out how to do this. Any suggestions?

You can do it easily with help of WinRAR:
#setlocal
#echo off
set path="C:\Program Files\WinRAR\";%path%
forfiles /s /m *.jpg /C "cmd /c winrar.exe a -afzip "#fname.zip" "#fname.eps" "#fname.jpg"
pause

Here is my example with windows native zip.exe. It looks for only *.eps files inside of current directory (because you have pair of files with the same name and different extensions), then it extracts filename, adds .eps and .jpg extensions and zip them with same name.
for /r %i in (*.eps) do zip %~ni.zip %~ni.eps %~ni.jpg
If you write inside of script then white with %%i
for /r %%i in (*.eps) do zip %%~ni.zip %%~ni.eps %%~ni.jpg

Related

Moving files from more than one folder to the parent directory using CMD

I have a folder Target contains multiple folders,
each folder contains one file with the same name of the folder
I want to move the files in folders Part1,Part2,Part3,Part4 and Part5
to parent folder ("Target" in this case) using cmd then delete the folders.
The result should be like that :
In Linux i could've used mv Part*\*.* ..
I've tried copy "Part*\*" "" command,
but it doesn't work.
Use a For loop. The key to getting directory names in this code is "dir /a:d" which only lists directories. I put that into the %%a variable. Use %~dp0 to refer to the directory the batch file is in. If your bat is somewhere else, do a find and replace all for that to the directory path you need. Lastly use RMDIR to remove each folder with /q /s to make it silent and remove all files within the directory (part1 part2 etc...) and the directories themselves.
#echo off
for /f "tokens=* delims=" %%a in ('dir /a:d /b "%~dp0"') do (
copy "%~dp0%%a\*.*" "%~dp0"
RMDIR /q /s "%~dp0%%a"
)
In the Windows Command Prompt, copy "Part*\*" "" cannot work, because wildcards are only permitted in the last element of a path but not somewhere in the middle.
To work around this, use a for /D loop to resolve wildcards in Part*, then let copy deal with the remaining ones:
for /D %I in ("Part*") do #copy "%~I\*" ".."
To move the files rather than to copy, simply replace copy by move. If you want to remove empty sub-directories then, append rd using &&:
for /D %I in ("Part*") do #move "%~I\*" ".." && #rd "%~I"
To use the above code fragments in a batch-file, ensure to double all the %-signs.

How to list all folders on specified drives with folder name first then gap then full path to folder?

dir i:\ j:\ k:\ /b /s /a:-D >c:\Users\Jason\Desktop\allFolderFilesOn_I_J_K.txt
This works great, but I am after a custom output, foldername full_path
Is this possible and if so how do I achieve this?
If I understand correctly, you don't want any files, but for every folder instead of C:\windows\system32 you want an output like system32 C:\Windows\
This can be done with the following command:
(for /d /r "D:\" %a in (*) do #echo %~nxa %~dpa)>c:\Users\Jason\Desktop\allFolderFilesOn_I_J_K.txt
where /d means "Directories only"
/r "Recursive" ("down the folder tree")
"D:\" the starting point
%~nxa the last element (the folder name)
%~dpa the drive/path to the folder
Note: this is command line syntax. For use in a batch file, replace each % with %%

How do you loop inside sub directories in windows, and repeat command using windows batch scripting

I am on Windows 10. I have a folder with sub folder. All subfolders have "Subs" folder inside them. I want to loop through all subdirectories, goto Subs directory, unrar a file, Goto next subdirectory and repeat.
I tried below script but could not get to work.
#echo off
setlocal enableextensions enabledelayedexpansion
set "rootFolder=C:\Users\MNM\MAT"
echo ----------------------------------------------------------------------
for /d /r "%rootFolder%" %%a in (.) do (
set mypath=%cd%
#echo %mypath%
cd %%a
set mypath=%cd%
#echo %mypath%
cd Subs
set mypath=%cd%
#echo %mypath%
C:\Users\MNM\MAT\unrar e *subs.rar C:\Users\MNM\mat2\
cd C:\Users\MNM\MAT
)
This simple task can be done with just a single command line:
#echo off
for /R "%USERPROFILE%\MAT" %%I in ("*subs.rar") do "%USERPROFILE%\MAT\UnRAR.exe" x -c- -idcdp -y "%%I" "%USERPROFILE%\mat2\"
USERPROFILE is a predefined Windows Environment Variable which is on your computer for your user account defined with value C:\Users\MNM.
The command FOR searches in directory C:\Users\MNM\MAT and all its non hidden subdirectories because of /R for non hidden files matching the pattern *subs.rar. Each file name found is assigned with full path to loop variable I.
UnRAR is executed for each found RAR archive file for extracting the archive to directory C:\Users\MNM\mat2 with extracting also the directory structures inside the RAR archive file because of command x instead of e. Existing files in destination directory (tree) are automatically overwritten because of -y. The switches -c- and -idcdp are for displaying less information during extraction process.
For a brief description of used and additionally available switches of UnRAR run in command prompt window UnRAR without any parameter or with /? as parameter. A complete description of the commands and switches of UnRAR can be found in text file Rar.txt in program files folder of WinRAR if that shareware application is also installed and not just the freeware UnRAR.
It is absolutely not needed to change into the directory containing the RAR archive file on extracting all RAR archives into same destination directory as it can be seen here.
This is one possible way if I understood your folder structure correctly:
#echo off
set "Base=C:\Users\MNM\MAT"
echo ----------------------------------------------------------------------
for /F "delims=" %%A in (
'dir /B/S "%Base%\*subs.rar" ^| findstr /i "^%Base:\=\\%\\[^\\]*\\Subs\\[^\\]*subs.rar$"'
) do Echo "C:\Users\MNM\MAT\unrar.exe" e "%%~fA" "C:\Users\MNM\mat2\"
the for /f will parse the output of the dir and findstr
dir will iterate all *subs.rar in the tree starting from %Base%
the complex RegEx in findstr will filter the rar's to those in a folder subs in a subfolder of %Base%
as a backslash is an escape char in a RegEx, literal backslashes have to be doubled.
If the output looks ok remove the echo in the last line.
Just because recursing all subdirectories and extracting all *subs.rar files wasn't requested here's an example that is based upon my assumptions:
#ECHO OFF
SET "rootDir=%USERPROFILE%\MAT"
IF /I NOT "%CD%"=="%rootDir%" CD /D "%rootDir%"
FOR /D %%A IN (*
) DO IF EXIST "%%A\Subs\*subs.rar" UNRAR e "%%A\Subs\*subs.rar" mat2\

exclude *.lyx~ files in batch (windows)

I just created the following batch file which saves all my lyx documents as tex files:
cd /d "D:\"
:: if the "for"-command is executed from the command line, just use "%" rather than "%%"
for /R %%g in (*.lyx) do "C:\Program Files (x86)\LyX 2.1\bin\lyx.exe" --force-overwrite --export pdflatex "%%g"
The problem is now that instead of the *.lyx files the batch uses the *.lyx~ files which are as far as I know some kind of backup files and don't contain the latest content.
How can I modify the batch file such that it takes the *lyx files rather than the *.lyx~ files?
Any suggestion would be great help.
Best :-)
PS: If I type this code in the command line (without using the batch), everything is fine.
#Edit1: added tokens option. Now it works in subdirs with spaces.
Modify your for loop to:
for /F "tokens=*" %%g in ('dir /b /s *.lyx') do if "%%~xg" equ ".lyx" (
"C:\Program Files (x86)\LyX 2.1\bin\lyx.exe" --force-overwrite --export pdflatex "%%g"
)
Another solution would be to use forfiles.
As for the 3rd comment, I think it does both but it does the .lyx~ at the end.
To see the output of a batch file simply launch it from a cmd window.

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