0

假设我的 unix 数据库中有一个 .txt 文件:events.txt 包含 3 列和 4 条记录,如下所示:

Name     DateofBirth                           City
Alex     2016-02-22 15:12:21.244000            London
John     2016-02-24 15:12:21.244000            Paris
Harry    2016-02-23 16:17:21.254000            Moscow
Karry    2016-02-23 11:12:21.271000            Berlin

我想编辑此表或创建一个新表,该表必须包含名为 DOB_epoch 的第 4 列(作为第 2 列 DateofBirth 的纪元值),如下所示:

Name     DateofBirth                           City       DOB_epoch
Alex     2016-02-22 15:12:21.244000            London     9632587410
John     2016-02-24 15:12:21.244000            Paris      9871236540
Harry    2016-02-23 16:17:21.254000            Moscow     9478523690
Karry    2016-02-23 11:12:21.271000            Berlin     9321456870

在 unix 中创建此类表列的命令应该是什么?

4

2 回答 2

0

使用“while”循环很容易。假设您要生成一个“events2.txt”文件:

对于 Linux:

#!/bin/bash

while read line;
do
    timedate=`echo $line | egrep -o "20.*[0-9]" | cut -d '.' -f 1`
    if [[ $timedate ]]
    then
        timestamp=`date -d"$timedate" +%s`
        echo -e "$line\t$timestamp" >> events2.txt
    else
        echo -e "$line\tDOB_epoch" >> events2.txt
    fi
done < events.txt

对于 BSD,只需将时间戳行替换为:

timestamp=`date -j -f "%Y-%m-%d %H:%M:%S" "$timedate" +%s`
于 2016-04-11T15:05:49.400 回答
0

read您可以使用,date和,在一个简短的 shell 脚本中相当简单地做到这一点printf。例如:

#!/bin/sh

fname=${1:-/dev/stdin}

c=0
while read -r nm dt tm ci; do
    [ "$c" -eq '0' ] && {
        printf "%-8s %-30s %-10s DOB_epoch\n" "$nm" "$dt" "$tm"
        c=1
        continue
    }
    epoch=$(date -d "${dt} ${tm}" +%s)
    printf "%-8s %-30s %-10s %s\n" "$nm" "$dt $tm" "$ci" "$epoch"
done < "$fname"

使用/输出

$ sh epochbd.sh dat/epochbd.txt
Name     DateofBirth                    City       DOB_epoch
Alex     2016-02-22 15:12:21.244000     London     1456175541
John     2016-02-24 15:12:21.244000     Paris      1456348341
Harry    2016-02-23 16:17:21.254000     Moscow     1456265841
Karry    2016-02-23 11:12:21.271000     Berlin     1456247541

我没有计算间距字符,因此您可能需要将printf字段宽度修饰符调整一两个字符。检查以确保您的版本read支持这些-r选项(否则,将其删除)。

于 2016-04-11T15:32:11.880 回答