【问题标题】:replacing timestamp with date using sed使用 sed 将时间戳替换为日期
【发布时间】:2019-07-02 14:14:43
【问题描述】:

当使用 SED 将时间戳替换为人类可读的日期时,时间戳总是替换为纪元日期加上放置在“\”之后的值

我有这个使用 Perl 的例子,但更喜欢使用 sed。我尝试了不同的转义序列并引用“'`等。

sed -re "s/([0-9]{10})/$(date -d @\1)/g" mac.txt

输入(一个字符串):

834|task|3||1561834555|Ods|12015|info|Task HMI starting 837|task|3||1561834702|Nailsd|5041|info|Configured with engine 6000.8403 (/opt/NAI/LinuxShield/engine/lib/liblnxfv.so), dats 9297.0000 (/opt/NAI/LinuxShield/engine/dat), 197 extensions, 0 extra drivers 

预计日期转换,但结果是:

834|task|3||Wed Dec 31 19:00:01 EST 1969|Ods|12015|info|Task HMI starting 837|task|3||Wed Dec 31 19:00:01 EST 1969|Nailsd|5041|info|Configured with engine 6000.8403 (/opt/NAI/LinuxShield/engine/lib/liblnxfv.so), dats 9297.0000 (/opt/NAI/LinuxShield/engine/dat), 197 extensions, 0 extra drivers 838|task.

基本上: 这就是所谓的:

$(date -d @\1) instead of $(date -d @\1561834555)

【问题讨论】:

    标签: shell date sed gnu


    【解决方案1】:

    sed 永远不会看到$(date -d @\1) -- shell 在 sed 启动之前 执行了该命令替换。

    你可以这样:

    sed -Ee 's/([0-9]{10})/$(date -d @\1)/g' -e 's/^/echo "/' -e 's/$/"/' mac.txt | sh
    

    (注意单引号,防止外壳进行任何扩展)

    然而,使用内置日期工具的语言更为明智。 GNU awk:

    gawk -F '|' -v OFS='|' '{
        for (i=1; i<=NF; i++)
            if ($i ~ /^[0-9]{10}$/)
                $i = strftime("%c", $i)
        print
    }' mac.txt
    

    可能会安装 Perl:

    perl -MPOSIX=strftime -pe 's{\b(\d{10})\b}{ strftime("%c", localtime $1) }ge' mac.txt
    # or, this is more precise as it only substitutes *fields* that consist of a timestamp
    perl -MPOSIX=strftime -F'\|' -lape '$_ = join "|", map { s/^(\d{10})$/ strftime("%c", localtime $1) /ge; $_ } @F' mac.txt
    

    【讨论】:

    • sed 命令运行良好,我目前无法测试 gawk,因为我没有安装它。您能澄清一下 -e 's/^/echo "/' -e 's/$/"/' 的作用吗?我现在只为当前项目学习 sed。非常感谢
    • 等一下,我想我明白了... 将 echo " 放在行首, " 在行尾放置 echo "$date( -d @1155....)"。对吗?
    • 差不多。在没有|sh 的情况下运行它,你会看到它的作用。我正在构建 shell 命令,因此可以在 shell 中评估 date 命令替换。
    • @vintnes,我看到了你的回答,但我无法对此发表评论。我认为 perl 比 gawk 更便携。
    • 感谢 Glenn,您对我们的帮助最大
    猜你喜欢
    • 2020-07-06
    • 1970-01-01
    • 2016-11-26
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2022-01-08
    相关资源
    最近更新 更多