在 CentOS 上“批量转换时间戳”常见有几种场景,下面按最常用的方式给你示例,你可以直接套用。
date -d @1700000000
输出示例:
Mon Nov 13 22:13:20 CST 2023
假设 ts.txt 内容如下:
1700000000
1700001000
1700002000
while read ts; do
date -d "@$ts"
done < ts.txt
awk '{print strftime("%F %T", $1)}' ts.txt
毫秒要除以 1000:
while read ts; do
date -d "@$(echo "$ts / 1000" | bc -l | cut -d. -f1)"
done < ts.txt
或 awk:
awk '{print strftime("%F %T", $1/1000)}' ts.txt
例如输出:
2023-11-13 22:13:20
while read ts; do
date -d "@$ts" "+%Y-%m-%d %H:%M:%S"
done < ts.txt
假设日志:
error at 1700000000
error at 1700001000
sed -E 's/([0-9]{10})/$(date -d @\1 "+%Y-%m-%d %H:%M:%S")/e' log.txt
⚠️ 注意:-E + e 需要 GNU sed(CentOS 默认支持)
例如:
file_1700000000.log
for f in *; do
ts=$(echo "$f" | grep -oE '[0-9]{10}')
[ -n "$ts" ] && echo "$f -> $(date -d @$ts)"
done
while read t; do
date -d "$t" +%s
done < time.txt
| 场景 | 推荐命令 |
|---|---|
| 秒级批量 | awk '{print strftime("%F %T", $1)}' file |
| 毫秒级 | awk '{print strftime("%F %T", $1/1000)}' file |
| 自定义格式 | date -d @ts "+%Y-%m-%d %H:%M:%S" |
| 日志替换 | sed -E 's/ts/replace/e' |
如果你能贴出具体数据格式(文件内容 / 日志片段),我可以帮你写完全可直接用的脚本。