简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM