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

前端 未结 2 1930
名媛妹妹
名媛妹妹 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:37

    $ mv /directory/* /directory/*$(date (+ '%Y%m%d')
    

    This does not work, because the * is expanded to a list of all files, so after the expansion the command will be something like:

    mv /directory/file1 /directory/file2 /directory/file3 /directory/file1_date /directory/file1_date ...
    

    So you have specified many destinations, but the syntax for mv allows only one single destination.

    for f in *; do mv $ $f.$(date +'_%m%d%y'); done
    

    Here you forgot the f after the $, that's why you get the error message.

    for f in *; do mv $f $f.$(date +'%m%d%y'); done
    

    I think this should work now, but don't forget to quote all the variables!

    Finally:

    for f in *; do mv "$f" "$f.$(date +'%m%d%y')"; done
    

    Edit: When there are characters directly after a variable, it's good practice to use {} to make clear that they are not part of the variable name:

    for f in *; do mv "$f" "${f}.$(date +'%m%d%y')"; done
    

提交回复
热议问题