views:

102

answers:

6

I am new to MS batch programing.

I want to copy files with matching regex to destination with same directory structure. If I use dir /b /s, I get full path of source then how can I get the relative path from source path?

I want DOS based batch script equivalent of something like this in bash script,

file_list=`find ./abc/test -name "*.c"`
for file_n in $file_list
do
    cp $file_n $targetdir/$file_n
done
A: 

I think the easier way, is to simply use pushd/popd:

pushd abs/test
file_list=`find . -name "*.[ch]"`
for file_n in $file_list
do
    cp $file_n $targetdir/$file_n
done
popd
notnoop
I want DOS based batch script equivalent of this. Sorry for being unclear.
vinit dhatrak
+4  A: 

Generally speaking source control is more appropriate than taking backups if source files...

Sander Rijken
+1 Cannot agree more. Assuming that the repository is on a different drive.
notnoop
A: 

You can use tar with a pipe to copy the directory hierarchy properly:

find . -name '*.[ch]' -exec tar cf - '{}' '+' | tar xf - -C $targetdir
Adam Rosenfield
A: 
tar cvf backup-`date +%Y%m%d`.tar `find . -name "*.[ch]" -print`

will create a dated tar file of the required files. That's possibly easier to manage.

Brian Agnew
A: 

with batch,

@echo off
for /F %%A in ('dir /b/s c:\test\*.c c:\test\*.h') do (
  echo copy "%%A" c:\destination
)

remove the echo to actual copy

ghostdog74
@ghostdog74 ... it does not recreate the directory structure. Thats my actually problem.
vinit dhatrak
A: 

The robocopy command will probably do what you want, but you didn't say what version of Windows you have (or is it really DOS rather than CMD?).

robocopy -s sourcedir destdir *.c *.h

or xcopy might work for you

xcopy /s *.c \destdir\
xcopy /s *.h \destdir\
Dennis Williamson