Batch mv or rename in bash script - append date as a suffix

前端 未结 2 2011
名媛妹妹
名媛妹妹 2021-01-20 00:42

After much searching and trial and error, I\'m unable to do a batch mv or rename on a directory of files. What I\'d like to do is move or rename a

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-20 01:40

    The proper way to loop through files (and e.g., print their name) in the current directory is:

    for file in *; do
        echo "$file"
    done
    

    How will you append the date? like so, of course:

    for file in *; do
        echo "$file.$(date +%Y%m%d)"
    done
    

    And how are you going to do the move? like so, of course:

    for file in *; do
        mv -nv -- "$file" "$file.$(date +%Y%m%d)"
    done
    

    I've added:

    • -v so that mv be verbose (I like to know what's happening and it always impresses my little sister to watch all these lines flowing on the screen).
    • -n so as to no overwrite an otherwise existing file. Safety first.
    • -- just in case a file name starts with a hyphen: without --, mv would confuse with an option. Safety first.

    If you just want to look through the files with extension .banana, replace the for with:

    for file in *.banana; do
    

    of for files that contain the word banana:

    for file in *banana*; do
    

    and so on.

    Keep up with the bananas!

提交回复
热议问题