Append date to filename in linux

后端 未结 5 1330
感情败类
感情败类 2020-12-02 14:38

I want add the date next to a filename (\"somefile.txt\"). For example: somefile_25-11-2009.txt or somefile_25Nov2009.txt or anything to that effect

Maybe a script w

相关标签:
5条回答
  • 2020-12-02 14:50

    a bit more convoluted solution that fully matches your spec

    echo `expr $FILENAME : '\(.*\)\.[^.]*'`_`date +%d-%m-%y`.`expr $FILENAME : '.*\.\([^.]*\)'`
    

    where first 'expr' extracts file name without extension, second 'expr' extracts extension

    0 讨论(0)
  • 2020-12-02 14:53

    You can use backticks.

    $ echo myfilename-"`date +"%d-%m-%Y"`"
    

    Yields:

    myfilename-25-11-2009
    
    0 讨论(0)
  • 2020-12-02 15:07

    I use this script in bash:

    #!/bin/bash
    
    now=$(date +"%b%d-%Y-%H%M%S")
    FILE="$1"
    name="${FILE%.*}"
    ext="${FILE##*.}"
    
    cp -v $FILE $name-$now.$ext
    

    This script copies filename.ext to filename-date.ext, there is another that moves filename.ext to filename-date.ext, you can download them from here. Hope you find them useful!!

    0 讨论(0)
  • 2020-12-02 15:09
    cp somefile somefile_`date +%d%b%Y`
    
    0 讨论(0)
  • 2020-12-02 15:13

    There's two problems here.

    1. Get the date as a string

    This is pretty easy. Just use the date command with the + option. We can use backticks to capture the value in a variable.

    $ DATE=`date +%d-%m-%y` 
    

    You can change the date format by using different % options as detailed on the date man page.

    2. Split a file into name and extension.

    This is a bit trickier. If we think they'll be only one . in the filename we can use cut with . as the delimiter.

    $ NAME=`echo $FILE | cut -d. -f1
    $ EXT=`echo $FILE | cut -d. -f2`
    

    However, this won't work with multiple . in the file name. If we're using bash - which you probably are - we can use some bash magic that allows us to match patterns when we do variable expansion:

    $ NAME=${FILE%.*}
    $ EXT=${FILE#*.} 
    

    Putting them together we get:

    $ FILE=somefile.txt             
    $ NAME=${FILE%.*}
    $ EXT=${FILE#*.} 
    $ DATE=`date +%d-%m-%y`         
    $ NEWFILE=${NAME}_${DATE}.${EXT}
    $ echo $NEWFILE                 
    somefile_25-11-09.txt                         
    

    And if we're less worried about readability we do all the work on one line (with a different date format):

    $ FILE=somefile.txt  
    $ FILE=${FILE%.*}_`date +%d%b%y`.${FILE#*.}
    $ echo $FILE                                 
    somefile_25Nov09.txt
    
    0 讨论(0)
提交回复
热议问题