0
votes

In Linux I have a permanent directory structure which stores 5 different types of files for each month of the year going back to 2005, like so

2005/01/file1 file2 file3 file4 file5

2005/02/file1 file2 file3 file4 file5

...

2015/11/file1 file2 file3 file4 file5

2015/12/file1 file2 file3 file4 file5

I need to replace each instance of file1 from an identical temporary directory structure, except each leaf in the temporary structure only has file1 (file2/3/4/5 do not exist). How can I do one bulk command to rename each file1 to file1.bak in the permanent structure, and then a command to copy each new file1 instance to the proper location in the permanent structure?

3
You can try rename 1 1.bak 20??/??/file1. Or you can use a for loop. for dir in 20??/??; do mv ${dir}/file1 ${dir}/file1.bak. As for copying to permanent directory, it's just a matter of prefixing the parent directory and using the same logic of the for loop. - alvits

3 Answers

1
votes

I'd first start with the multiple rename -- cd into the root directory you want to search through .. (Above /2015/).

find spec -name "*file1" -exec sh -c 'echo mv "$1" "$(echo "$1" | sed s/file1\$/bak.file1/)"' _ {} \;

Then simply do a mass cp if you are certain the file structures are the same. Lets assume we're working with /var/www/2015/ and /var/www/COPY/ and those two directories are the same structure internally ... then simply

cp -R /var/www/COPY/* /var/www/2015/

Whatever files DON'T EXIST in 2015 that do in COPY will be copied FROM /var/www/COPY/ TO /var/www/2015/ without overwriting existing files (file2, 3 4 5 etc).

1
votes

You can use this command to rename all file1 to file1.bak:

find . -name file1 | sed -e "p;s/file1/file1.bak/" | xargs -n2 mv

Then copy new files file1 with cp -R

0
votes

Another alternative that may or may not be useful for you is vidir, which is in the moreutils package in Debian-family distros.

It opens your directory in your $EDITOR (or your system's default editor), and you can edit files in here to your heart's content. You can then just use your $EDITOR's search/replace function to rename your files and save.