在UNIX外壳调用函数的值结果替换值 [英] Substitute value with result of calling function on value in unix shell
问题描述
我有一个看起来像这样的文本流:
I have a text stream that looks like this:
----------------------------------------
s123456789_9780
heartbeat:test @ 1344280205000000: '0'
heartbeat:test @ 1344272490000000: '0'
那些漫长的数字是在微秒时间戳。我想运行通过某种管道此输出将改变这些时间戳来一个更人性化理解的日期。
Those long numbers are timestamps in microseconds. I would like to run this output through some sort of pipe that will change those timestamps to a more human-understandable date.
我只给定时间戳(含以下冒号)日期命令可以做到这一点,
I have a date command that can do that, given just the timestamp (with the following colon):
$ date --date=@$(echo 1344272490000000: | sed 's/.......$//') +%Y/%d/%m-%H:%M:%S
2012/06/08-10:01:30
我想用这样的事情结束了:
I would like to end up with something like this:
----------------------------------------
s123456789_9780
heartbeat:test @ 2012/06/08-12:10:05: '0'
heartbeat:test @ 2012/06/08-10:01:30: '0'
我不认为 SED
让我来匹配的时间戳,并调用它的外壳函数的值(替换它,虽然我很高兴能够成为显示错误的)。也许 AWK
能做到吗?我不是很熟悉的 AWK
。
I don't think sed
will allow me to match the timestamp and replace it with the value of calling a shell function on it (although I'd love to be shown wrong). Perhaps awk
can do it? I'm not very familiar with awk
.
这似乎棘手,我的另一部分是让那些不不加修改地通过匹配的行。
The other part that seems tricky to me is letting the lines that don't match through without modification.
我当然可以写一个Python程序,将做到这一点,但如果可能的话,我宁愿保持这个壳(这是一个shell脚本内部产生的,我宁愿没有对外界的依赖关系的文件)。
I could of course write a Python program that would do this, but I'd rather keep this in shell if possible (this is generated inside a shell script, and I'd rather not have dependencies on outside files).
推荐答案
猛砸一点点SED,preserving输入的空白:
Bash with a little sed, preserving the whitespace of the input:
while read -r; do
parts=($REPLY)
if [[ ${parts[0]} == "heartbeat:test" ]]; then
dateStr=$(date --date=@${parts[2]%000000:} +%Y/%d/%m-%H:%M:%S)
REPLY=$(echo "$REPLY" | sed "s#[0-9]\+000000:#$dateStr#")
fi
printf "%s\n" "$REPLY"
done
这篇关于在UNIX外壳调用函数的值结果替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!