需求说明
csv 文件以逗号拆分列,时间戳为 毫秒级别的
> 下载日志文件,日志内有时间戳,展示不够直观。预期:将毫秒的时间戳修改为时间。
完整代码
replace.sh
cat replace.sh
#!/bin/bash
fileName=$1
outputFileName=$2
echo '' > $outputFileName;
cat $fileName | while read line
do
getDate=$(echo "$line" | awk -F ',' '{print $2}')
dateTime=$(date -j -f "%s" "${getDate: 0: 10}" "+%Y-%m-%d %H:%M:%S");
replace=$(echo "$line" | sed "s/$getDate/$dateTime.${getDate: 10: 13}/g");
echo $replace >> $outputFileName;
done
执行替换操作
sh ./replace.sh inputFile.csv output.csv
代码解析
逐行读取文件
#!/bin/bash
cat $fileName | while read line
do
echo $line;
done
解析出时间戳在的列
csv 以逗号拆分列,且时间戳 第二列中。
#!/bin/bash
cat $fileName | while read line
do
getDate=$(echo "$line" | awk -F ',' '{print $2}')
done
拆分时间戳并转化为时间
#!/bin/bash
cat $fileName | while read line
do
getDate=$(echo "$line" | awk -F ',' '{print $2}')
## 拆分时间戳并转化为时间
dateTime=$(date -j -f "%s" "${getDate: 0: 10}" "+%Y-%m-%d %H:%M:%S");
done
替换当前行中的时间戳
#!/bin/bash
cat $fileName | while read line
do
getDate=$(echo "$line" | awk -F ',' '{print $2}')
dateTime=$(date -j -f "%s" "${getDate: 0: 10}" "+%Y-%m-%d %H:%M:%S");
## 替换当前行中的时间戳
replace=$(echo "$line" | sed "s/$getDate/$dateTime.${getDate: 10: 13}/g");
done
将替换后的行写入到新的文件
#!/bin/bash
cat $fileName | while read line
do
getDate=$(echo "$line" | awk -F ',' '{print $2}')
dateTime=$(date -j -f "%s" "${getDate: 0: 10}" "+%Y-%m-%d %H:%M:%S");
## 替换当前行中的时间戳
replace=$(echo "$line" | sed "s/$getDate/$dateTime.${getDate: 10: 13}/g");
## 将替换后的行写入到新的文件
echo $replace >> $outputFileName;
done
excel 中单元格格式调整
yyyy/m/d hh:mm:ss.000
结果展示
Excel
=(B2/1000+8*3600)/86400+70*365+19