Find the answer to your Linux question:
Results 1 to 3 of 3
Hi everybody, I need to rename files adding a timestamp to there name. eg : rename myfile in myfile-2008-03-05 I need to do that on every file in a directory ...
  1. #1
    Just Joined!
    Join Date
    Mar 2008
    Posts
    11

    Question Advanced file renaming

    Hi everybody,
    I need to rename files adding a timestamp to there name.
    eg : rename myfile in myfile-2008-03-05

    I need to do that on every file in a directory and its subdirectories.
    So I wrote the following script :
    Code:
    find * -type f -exec mv "{}" "{}-2008-05-03" \;
    It seems to work fine

    Now, most of my directories store windows clients files. Which means those files have extensions and users see them with icons corresponding to this extension.
    That's why I'd like to run my script adding the timestamp before the extension
    eg : rename report.xls in report-2008-03-05.xls

    Does anyone have a brilliant idea to do so ?
    Thanks for your help.
    Santiago

  2. #2
    Linux User
    Join Date
    Jun 2007
    Posts
    318
    You'd have to write a script. Here's one I came up with that seems to work. Use at your own risk:

    Code:
    #!/bin/bash
    
    typeset -i len
    shopt -s extglob
    curdte="`date "+%Y-%m-%d"`"
    for oldfle in $(find * -type f)
        do
            dir="`dirname $oldfle`"
            fle="`basename $oldfle`"
            tmp="${fle%.*([[:alnum:]])}"
            len=${#tmp}
            lft="`echo "$fle^$len" | awk -F^ '{print substr($1,1,$2)}'`"
            len=len+1
            rt="`echo "$fle^$len" | awk -F^ '{print substr($1,$2)}'`"
            newfle="${dir}/${lft}-${curdte}${rt}"
    
            echo $oldfle
            echo $newfle
            mv $oldfle $newfle
        done
    Note that if you run this script a 2nd time on a directory you'll get files like:
    report-2008-03-05-2008-30-05.xls

    Edit: Note that if there are spaces in the filenames this script will break.

  3. #3
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    This should work, not tested though.

    Code:
    #!/bin/bash
    
    DATE="$(date "+%Y-%m-%d")"
    
    find * -type f | while read file
    do
      ext="${file##*.}"
      if [ ! "$file" == "$ext" ]
      then
        old="${file%.${ext}}"
        new="${old}-${DATE}.${ext}"
      else
        new="${file}-${DATE}"
      fi
      echo $new
    done
    If a file is on the form a.b, it ends as a-<date>.b.
    If a file is on the form a.b.c, it ends as a.b-<date>.c
    if a file has no extension, it ends being called a-<date>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...