【发布时间】:2016-10-13 14:55:14
【问题描述】:
我正在尝试获取一些大小为零的文件并将其插入文本。我创建了一个简单的脚本,每 15 分钟将其放入 crontab 中。
我在阅读此问题后使用find 在How to find all Zero bytes files in directory including subdirectories 之前找到它。
这里是脚本。
#!/usr/bin/bash
statPath=/opt/player/for_test/testing
date=`date +%Y%m%d` #Untuk mengambil tanggal (YYYY-MM-DD)
cm=$(date +%M)
host=`hostname`
for n in `find $statPath -size 0`
do
if [ $cm -ge 0 ] && [ $cm -le 15 ];then
echo $date"00""|"$host"|"0x00"|"0 >> $n
elif [ $cm -ge 16 ] && [ $cm -le 30 ];then
echo $date"15""|"$host"|"0x00"|"0 >> $n
elif [ $cm -ge 31 ] && [ $cm -le 45 ];then
echo $date"30""|"$host"|"0x00"|"0 >> $n
elif [ $cm -ge 46 ] && [ $cm -le 59 ];then
echo $date"45""|"$host"|"0x00"|"0 >> $n
fi
done
运行脚本前testing目录中的文件
-rw-r--r-- 1 root root 0 Jun 13 13:46 Server01_2016061313_45.log
-rw-r--r-- 1 root root 0 Jun 13 14:01 Server01_2016061314_00.log
-rw-r--r-- 1 root root 0 Jun 13 14:16 Server01_2016061314_15.log
-rw-r--r-- 1 root root 0 Jun 13 14:31 Server01_2016061314_30.log
-rw-r--r-- 1 root root 0 Jun 13 14:46 Server01_2016061314_45.log
-rw-r--r-- 1 root root 0 Jun 13 15:01 Server01_2016061315_00.log
运行脚本后在testing目录中的文件。
-rw-r--r-- 1 root root 28 Jun 13 13:46 Server01_2016061313_45.log
-rw-r--r-- 1 root root 28 Jun 13 14:01 Server01_2016061314_00.log
-rw-r--r-- 1 root root 28 Jun 13 14:16 Server01_2016061314_15.log
-rw-r--r-- 1 root root 28 Jun 13 14:31 Server01_2016061314_30.log
-rw-r--r-- 1 root root 28 Jun 13 14:46 Server01_2016061314_45.log
-rw-r--r-- 1 root root 28 Jun 13 15:01 Server01_2016061315_00.log
我得到的结果是所有文件都以相同的格式更改。我在下午 3:34 运行脚本。
root@Server01:/opt/player/for_test/testing# more Server01_2016061313_45.log
2016061330|Server01|0x00|0
root@Server01:/opt/player/for_test/testing#
root@Server01:/opt/player/for_test/testing# more Server01_2016061314_15.log
2016061330|Server01|0x00|0
预期结果
For log with "00" minute, the result is 2016061300|Server01|0x00|0
For log with "15" minute, the result is 2016061315|Server01|0x00|0
For log with "30" minute, the result is 2016061330|Server01|0x00|0
For log with "45" minute, the result is 2016061345|Server01|0x00|0
有什么简单的方法可以做到这一点吗?我有点卡在这里。
【问题讨论】:
-
所有文件都以相同的格式更改,因为您使用的是在循环之前定义的
$cm。 -
所以我应该在循环内移动变量
cm? -
哦,等等,我看错了你的问题。所以你想用
cm来表示当前15分钟的块?那么这应该没问题。我刚刚对其进行了测试,它工作正常 - 作为旁注,您可能需要在之前预处理$cm,这样您就不必使用这个巨大的 if/else 条件。 -
您不需要该变量,因为您的预期结果没有使用它。
-
我认为您打算使用找到的文件名来决定文件内容。
标签: bash file replace cron find