使用时间戳bash删除文件中超过一小时的行

使用时间戳bash删除文件中超过一小时的行,bash,sed,timestamp,Bash,Sed,Timestamp,有一点麻烦,试图让下面的工作 我有一个包含hostname:timestamp的文件,如下所示: hostname1:1445072150 hostname2:1445076364 我正在尝试创建一个bash脚本,该脚本将查询该文件(使用cron作业)以检查时间戳是否超过1小时,如果是,请删除该行。 下面是我到目前为止所做的,但它似乎没有删除文件中的行 #!/bin/bash hosts=/tmp/hosts current_timestamp=$(date +%s) while read

有一点麻烦,试图让下面的工作

我有一个包含
hostname:timestamp
的文件,如下所示:

hostname1:1445072150
hostname2:1445076364
我正在尝试创建一个bash脚本,该脚本将查询该文件(使用cron作业)以检查时间戳是否超过1小时,如果是,请删除该行。 下面是我到目前为止所做的,但它似乎没有删除文件中的行

#!/bin/bash

hosts=/tmp/hosts
current_timestamp=$(date +%s)

while read line; do
    hostname=`echo $line | sed -e 's/:.*//g'`
    timestamp=`echo $line | cut -d ":" -f 2`
    diff=$(($current_timestamp-$timestamp))
    if [ $diff -ge 3600 ]; then
            echo "$hostname - Timestamp over an hour old. Deleting line."
            sed -i '/$hostname/d' $hosts
    fi
done <$hosts
#/bin/bash
hosts=/tmp/hosts
当前时间戳=$(日期+%s)
读行时;做
主机名=`echo$line | sed-e's/:*//g'`
时间戳=`echo$line | cut-d:'-f2`
差异=$($当前时间戳-$时间戳))
如果[$diff-ge 3600];然后
echo“$hostname-超过一小时的时间戳。正在删除行。”
sed-i'/$hostname/d'$hosts
fi

完成您要求的替代方案-使用
awk

awk -F: -v ts=$(date +%s) '$2 <= ts-3600 { next }' $hosts > $hosts.$$
mv $hosts.$$ $hosts
下一步之前
打印标准误差信息。如果必须将其写入标准输出,则需要安排将保留行写入带有
print>file
的文件,作为筛选条件后的替代操作(将
-v file=“$hosts.$$”
作为另一对参数传递给
awk
)。可以做的调整是无穷无尽的


如果文件大小较大,则将文件的相关小节复制一次到临时文件,然后复制到最终文件,比在原始代码中多次就地编辑文件更快。如果文件足够小,就没有问题。

脚本中的问题就在于这一行:

sed -i '/$hostname/d' $hosts
单引号内的变量不会展开为其值, 因此,该命令试图替换字面上的“$hostname”,而不是它的值。如果用双引号替换单引号, 变量将扩展到其值,这是您在此处需要的:

sed -i "/$hostname/d" $hosts
有可能的改进:

#!/bin/bash

hosts=/tmp/hosts
current_timestamp=$(date +%s)

while read line; do
    set -- ${line/:/ }
    hostname=$1
    timestamp=$2
    ((diff = current_timestamp - timestamp))
    if ((diff >= 3600)); then
        echo "$hostname - Timestamp over an hour old. Deleting line."
        sed -i "/^$hostname:/d" $hosts
    fi
done <$hosts
#/bin/bash
hosts=/tmp/hosts
当前时间戳=$(日期+%s)
读行时;做
设置--${line/://}
主机名=$1
时间戳=$2
((diff=当前_时间戳-时间戳))
如果((差异>=3600));然后
echo“$hostname-超过一小时的时间戳。正在删除行。”
sed-i“/^$hostname:/d”$hosts
fi

已完成对
diff=$((当前时间戳-时间戳))
的更改,并引用sed所需的扩展:
sed-i/$hostname/d“$hosts
Cheers@amdixon。这似乎成功了。非常感谢:)不用担心,代码几乎正常工作了。alreadyamdixon帮助我们找到了脚本的问题,但感谢改进,特别是解释了每一个问题(Y)这是一个好答案,因为在while循环中使用awk是一个坏主意。
#!/bin/bash

hosts=/tmp/hosts
current_timestamp=$(date +%s)

while read line; do
    set -- ${line/:/ }
    hostname=$1
    timestamp=$2
    ((diff = current_timestamp - timestamp))
    if ((diff >= 3600)); then
        echo "$hostname - Timestamp over an hour old. Deleting line."
        sed -i "/^$hostname:/d" $hosts
    fi
done <$hosts