将文件复制到子目录并重命名

时间:2014-06-29 00:28:45

标签: linux bash

您好,我目前正在编写一个bash文件,我正在尝试将文件复制到子目录中并将其重命名为修改的日期和时间

我知道如何使用

将其复制到子目录中
cp $1 subdirectory

但我如何同时将其重命名为2014-06-28-08-28-59(年 - 月 - 日 - 小时 - 分 - 秒)?

谢谢!

编辑:

还有一个问题我如何使用传入的参数mkdir目录?

就像我在做

./makedirectory directoryname

我想用$ 1的第一个参数o_O

创建一个目录

再次感谢!

3 个答案:

答案 0 :(得分:4)

在子目录中将文件名设置为 2014-06-28-08-28-59

cp $1 subdirectory/2014-06-28-08-28-59

如果要将日期动态设置为当前日期,您可能需要更多类似的内容:

cp $1 subdirectory/"$(date)"

与文件修改时间有关的内容:

cp $1 subdirectory/"$(stat -c %y $1)"

如果您要将信息附加到原始文件名:

cp $1 subdirectory/"$1--$(stat -c %y $1)"

这真的分解为:

  • 如果您要使用cp重命名文件,只需在要将其移至的路径末尾提供该文件名。
  • 您可以使用$( ... )中包含的命令的返回来以任何方式扩展功能。

答案 1 :(得分:3)

这应该复制文件,追加上次修改的文件:

#!/bin/bash
if [ -e $1 ]; then
    cp -v $1 subdirectory/$(stat -c %y $1 | awk '{print $1"_"$2}')-${1}
else
    echo "Error: file not found"
fi
exit

if语句首先检查文件是否存在。

这应该做同样的事情,但追加当前时间(以类似的格式):

#!/bin/bash
if [ -e $1 ]; then
    cp -v $1 subdirectory/$(date +%Y-%m-%d_%H:%M:%S)-${1}
else
    echo "Error: file not found"
fi
exit

答案 2 :(得分:0)

如果我们想在文件名之后放置日期/时间并且文件有扩展名怎么办?要在保留扩展名的同时处理带扩展名的文件,您需要这样的内容(以及一些完整性检查):

#!/bin/bash

## copy with date_time, usage:  cpwdt file dir

## test and validate input
test -n "$1" && test -n "$2" || { 
    echo "error: insufficient input, usage: ${0##*/} file dir"
    exit 1
}
test -r "$1" || { echo "error: unable to read '$1'"; exit 1; }
test -w "$2" || { echo "error: insufficient permissions for '$2'"; exit 1; }

## create timestamp (to insure it doesn't change throughout script)
tstamp="$(date +%Y%m%d-%H%M%S)"

## test target directory existence or create, exit if unable
test -d "$2" || mkdir -p "$2"
test -d "$2" || { echo "error: failed to create '$2'"; exit 1; }

## form filename, test, and copy to destination appending timestamp
basenm="${1%\.*}"
ext="${1##*\.}"

if test "${1}" == "${basenm}" ; then
    fname="${1}_${tstamp}" 
else
    fname="${basenm}_${tstamp}.${ext}"
fi

cp -a "$1" "${2}/${fname}"

exit 0

输入:

$ ls -1 file*
file_no_ext
file_w_ext.txt

$ cpwdt file_no_ext tmp
$ cpwdt file_w_ext.txt tmp

输出:

$ ls -1 tmp
file_no_ext_20140628-221759
file_w_ext_20140628-221819.txt

这可能会提供更多的灵活性和一些额外的检查。

相关问题