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

Viewed 162

I need to copy a file from one location to another while renaming the file with adding date and time stamp YYYYMMDDHHmmSS in this Format only using shell.

My Bash shell code:

cd $1
f1=Sup_Org_File_
for f in *.xml
do 
   cp -v "$f" $2/"${f1%}"$(date +%F%H:%M).xml
   cp -v "$f" $3/"${f1%}"$(date +%F%H:%M).xml
done
2 Answers

hope this helps you

for Bash shell Script

cd path_to_file
for f in *.xml
do 
   cp -v "$f" path_to_copy_file/"${f%.xml}"$(date +%Y%m%d%H%M%S).xml
done

Just "${f1%}" doesn't do anything useful; you want to put a pattern for something to actually remove after the %; and of course you probably want to remove a suffix from f, not from f1. (Giving your variables sensible names also helps.)

It's not clear what you expect $2 and $3 to contain, but they probably won't work correctly after you cd $1 (and all three of these should be quoted anyway).

Guessing a bit as to what you actually want, try this:

#!/bin/sh
d=$(date +'%F%H:%M)
for f in "$1"/*.xml
do
    # Trim directory prefix
    b=${f#$1/}
    # Trim .xml suffix
    b=${b%.xml}
    # Copy
    cp -v "$f" "$2/$b$d".xml
    cp -v "$f" "$3/$b$d".xml
done

There are no Bashisms here so I put a /bin/sh shebang on this.

Related