BASH: 复制多个文件并显示需要多长时间

BASH: Copy multiple files and show how long it takes

我的 bash 脚本中有这样一行:

cp -v /temp1/* /temp2/* >> $LOGFILE

$LOGFILE 基本上就是一个日志文件。我目前在 $LOGFILE 中得到的结果是这样的:

‘/temp1/file1’ -> ‘/temp2/file1’
‘/temp1/file2’ -> ‘/temp2/file2’
‘/temp1/file3’ -> ‘/temp2/file3’
‘/temp1/file4’ -> ‘/temp2/file4’

首先,我想去掉前缀“-”和尾随“-”。其次,我想显示当前时间(以 hh:mm 格式)或经过的时间,因此 $LOGFILE 将显示:

10:24 /temp1/file1 -> /temp2/file1
10:27 /temp1/file2 -> /temp2/file2

00:03 /temp1/file1 -> /temp2/file1
00:27 /temp1/file2 -> /temp2/file2

有人可以帮我解决其中一个或两个问题吗?

我认为 ‘’ 而不是 ' 或 " 是由于编码问题(例如 here)。你用什么打开 $LOGFILE?尝试使用 cat $LOGFILE

您可以使用类似的东西:

for fn in /temp1/*
do
    #hour and minutes
    d=$(date +%H:%M)
    # cp output
    c=$(cp -v $fn /temp2/)
    # echo
    echo $d $c >> $LOGFILE
done

我相信你必须为此使用一个循环,一个一个地复制文件,然后在每次复制之前手动打印日期:

(for i in test1/*; do \
   printf "%s: " $(date +"%M:%S"); \
   cp -v $i ${i/test1/test2} | sed "s|[\`\']||g"; \
 done) >> log.file

您看到的滑稽字符是由您的终端编码引起的。它们等同于 ` 和 ',所以我提供的 sed 语句应该可以工作(无法在本地测试,因为我没有您正在使用的任何编码)。

----- 编辑 -----

如果要查找目录下的所有个文件(不只是直接在test1中的那些),可以使用find-exec如下:

find test1 -type f -exec printf "%s: " $(date +"%M:%S") \; -exec echo {} \;

这将找到所有文件,运行 每个文件的两个命令。 {} 扩展为找到的文件名。 \; 告诉 find 命令已完成。执行 man find 了解更多信息。