2

I have a requirement to move all the files from multiple subdirectories into a single directory with adding timestamp to it.

I am having the below directory structure,

Interface/Temp/GoodsRecipt/GR123/abc.csv, cad.csv    
Interface/Temp/GoodsRecipt/GR456/abc.csv, cad.csv

I want to move the CSV files from the random directories into a single directory and add up the timestamp to the files. The result should be like below,

Interface/Temp/GoodsRecipt/GRout/abc05082014.csv,  cad05082014.csv, abc06032014.csv, cad06032014.csv

I need to write a shell script and run in independently for this operation. Any help on the shell script creation would be much appreciated.

0
INDIR='./Interface/Temp/GoodsRecipt'
OUTDIR='./Interface/Temp/GoodsRecipt/GRout'

mkdir -p "$OUTDIR"

find "$INDIR"/GR*/ -type f -name '*.csv' | while IFS= read f ; do
  fd=$(date +'%Y%m%d' -d @$(stat -c %Y "$f"))
  bn=$(basename "$f" .csv)
  mv "$f" "$OUTDIR/$bn$fd.csv"
done

NOTE: I haved used YYYYMMDD here instead of DDMMYYYY. There are many reasons why it is a superior date format, but one of the most important is that it is the only format that sorts correctly.

Another important reason is that it is unambiguous, because nobody uses YYYYDDMM. But 05082014 could mean "May 8th 2014" (if you're an American) or it could mean "August 5th 2014" (almost everywhere else in the world). It's unsafe to use that format because there's no way of telling which is the intended meaning.

If you insist on using DDMMYYYY, change the date command to date +'%d%m%Y':

  fd=$(date +'%d%m%Y' -d @$(stat -c %Y "$f"))
  • Hi, Thanks for your reply. I tried using the above code a create a .sh file, but it keeps failing. I am new to shell scripts and wanted to know if i have to do anything in addition to create a .sh file. – user3196136 Oct 27 '15 at 5:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.