Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script to copy files from one location to another location and rename add the current date to every file

Tags:

bash

shell

unix

I have a folder in my server which contains some files. These are automated that means everyday we get new files automatically which will overwrite the old ones. So want to take a back up for this data. How can i copy all these files in to a another folder by renaming the files with current date while copying.

ex : i have a folder named folder1 which contains 4 files. path for this folder is home/webapps/project1/folder1

  1. aaa.csv
  2. bbb.csv
  3. ccc.csv
  4. ddd.csv

now i want to copy all these four files in to a different folder named folder2. path for this folder is home/webapps/project1/folder2. while copying these files i want to rename each file and add the current date to the file. so my file names in folder2 should be..

  1. aaa091012.csv
  2. bbb091012.csv
  3. ccc091012.csv
  4. ddd091012.csv

I want to write a shell script for this. Please give me some idea or some sample scripts related to this.

like image 536
ran Avatar asked Sep 10 '12 15:09

ran


3 Answers

In bash, provided you files names have no spaces:

cd /home/webapps/project1/folder1 for f in *.csv do     cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv done 
like image 173
Stephane Rouberol Avatar answered Sep 26 '22 06:09

Stephane Rouberol


You could use a script like the below. You would just need to change the date options to match the format you wanted.

#!/bin/bash

for i in `ls -l /directroy`
do
cp $i /newDirectory/$i.`date +%m%d%Y`
done
like image 30
Lipongo Avatar answered Sep 24 '22 06:09

Lipongo


path_src=./folder1
path_dst=./folder2
date=$(date +"%m%d%y")
for file_src in $path_src/*; do
  file_dst="$path_dst/$(basename $file_src | \
    sed "s/^\(.*\)\.\(.*\)/\1$date.\2/")"
  echo mv "$file_src" "$file_dst"
done
like image 42
perreal Avatar answered Sep 22 '22 06:09

perreal