我有一个以下格式的文件:
"2004-04-19 12:25:57" 44 44
"2004-04-19 13:39:32" 36 36
"2004-04-19 14:00:53" 34 34
我需要 2 个新文件:
a) 一个文件,它将用从 1 开始的数字替换文件第一列的“时间”值,如下所示:
1 44 44
2 36 36
3 34 34
b) 另一个文件,它将用数字 unix tamestamp 数据替换文件第一列的“时间”值,如下所示:
1082377557 44 44
1082381972 36 36
1082383253 34 34
答案1
您可以使用这一bash
衬垫:
i=1; while IFS=' ' read a b c; do echo "$i $c" >>foo.txt; ((i+=1)); \
echo "$(date -d "${a#\"} ${b%\"}" '+%s')" "$c" >>bar.txt; done <file.txt
展开形式:
i=1
while IFS=' ' read a b c; do
echo "$i $c" >>foo.txt
((i+=1))
echo "$(date -d "${a#\"} ${b%\"}" '+%s')" "$c" >>bar.txt
done <file.txt
运行后foo.txt
会有:
1 44 44
2 36 36
3 34 34
并将bar.txt
有:
1082377557 44 44
1082381972 36 36
1082383253 34 34
答案2
awk:
awk '{
# store the time value (first 2 words)
timestamp = $1 " " $2
# shift the other fields 2 places (I wish this was simpler in awk)
for (i=3; i<=NF; i++) $(i-2) = $i
NF -= 2
# print to the line-numbers file
print NR, $0 > "file1"
# convert the timestamp and print to that file
gsub(/[-:"]/, " ", timestamp)
print mktime(timestamp), $0 > "file2"
}' file
mktime
需要 GNU awk(我认为)。
珀尔:
perl -MTime::Piece -anE '
BEGIN {
$, = " ";
open $f1, ">", "file1";
open $f2, ">", "file2"
}
$date = shift @F;
$time = shift @F;
say $f1 $., @F;
say $f2 Time::Piece->strptime("$date $time", "\"%Y-%m-%d %H:%M:%S\"")->epoch, @F
' file
答案3
好吧,冒着为你做作业的风险。给你。
假设您的数据位于名为 YOURFILENAME 的文件中,第一个 lineliner 添加行号和文件中的最后两个字段
count=1;cut -d" " -f 3,4 YOURFILENAME| while read line ; do echo $count $line;((++count)); done
第二行将把你的日期转换为纪元并打印出该行的其余部分(必须再添加一个 sed 来去掉引号,但我这样做又快又脏)
cut -d"\"" -f2 YOURFILENAME| while read line; do SWAP=$(date -d "$line" +\%s); sed -i "s/$line/$SWAP/g" YOURFILENAME;done ; sed 's/"//g' YOURFILENAME
请注意,这只是您可以执行此操作的一种方法。可能还有不少。
答案4
我会在 perl 中这样做:
#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
#open our files for output
open( my $output1, '>', "output_file_one.txt" ) or die $!;
open( my $output2, '>', "output_file_two.txt" ) or die $!;
#iterate the magic filehandle - <> - which reads either data piped from
#stdin, or opens files specified on command line. (Just like grep/awk/sed)
while (<>) {
#regex match the values out of your source file.
my ( $t, @values ) = m/^\"(.*)\" (\d+) (\d+)/;
#convert $t into a time object.
$t = Time::Piece->strptime( $t, "%Y-%m-%d %H:%M:%S" );
#use the "epoch" method to extract the numeric time from $t
print {$output1} join( " ", $t->epoch, @values );
# $. is the perl special var for current line number.
print {$output2} join( " ", $., @values );
}
close($output1);
close($output2);