我是KSH、grep、awk、sed等的新手
我的任务是:
我正在编写一个通过密钥库并打开它们的脚本。然后我想找到有效截止日期,并将其转换为时期。我可以就地执行,也可以将整个文件(包括编辑过的和未编辑过的部分)写入新文件,如果这样更容易的话。
我的输入如下:
Alias name: mycertname
Creation date: Dec 31, 1969
Entry type: entry type
Owner: owner info
Issuer: issuer info
Serial number: serial number
Valid from: 6/11/03 2:23 PM until: 6/6/23 2:23 PM
Certificate fingerprints: <...>
文件中有许多类似的输出。
有一个问题需要考虑。
1) 并不是所有这些证书都有一个有效的发件人行。
我已经建立了我计划用于将日期转换为时期的命令:
date +%s -d"string I cut from input"
我不知道该怎么做,就是格式化我的输出。
我理想的输出是这样的:
Alias name: mycertname 1686075780
或
Alias name: mycertname
1686075780
我的想法是:
awk '/^Alias/ { alias = $0 } /^Valid from:/ { sub(/.*until: /, ""); cmd = "date +%s -d "" $0 """; if((cmd | getline epoch) != 1) { epoch = "Broken timestamp" } close(cmd); print alias, epoch }' filename
即:
/^Alias/ { # When a line begins with "Alias"
alias = $0 # remember it
}
/^Valid from:/ { # When a line begins with "Valid from:"
sub(/.*until: /, "") # Remove everything before the until date
cmd = "date +%s -d "" $0 """ # build the shell command to execute
if((cmd | getline epoch) != 1) { # execute it, get its output
epoch = "Broken timestamp" # in case of failure, set easily
# recognizable replacement message.
# If you want to skip broken records like
# those without a timestamp, use "next"
# instead.
}
close(cmd) # close the pipe
print alias, epoch # print the remembered alias followed by
# the output of that command.
}