简体   繁体   English

使用包含字段文本的命令在 awk 中获取 shell 命令的 output

[英]Getting the output of a shell command in awk with command containing text from a field

I'm trying to parse a file for some dates in a specific format and get the 'seconds since the Epoch' to calculate absolute differences between the date and the current date.我正在尝试以特定格式解析某些日期的文件并获取“自纪元以来的秒数”以计算日期与当前日期之间的绝对差异。 I need to do this on each line using the 4th field, so I tried doing something like this:我需要使用第 4 个字段在每一行上执行此操作,因此我尝试执行以下操作:

"date --date=$4 +%s" | getline DUE
close("date --date=$4 +%s")
"date +%s" | getline CURR
close("date +%s")

Of course this doesn't quite work because awk interprets the $4 as a literal "$4".当然这并不完全有效,因为 awk 将 $4 解释为文字“$4”。 So I can't use variables inside that statement.所以我不能在该语句中使用变量。

I also tried creating 2 variables with the front of the command string and the ending with a third variable being those concatinated with $4 in the middle.我还尝试在命令字符串的前面创建 2 个变量,并以第三个变量结尾,即中间用 $4 连接的变量。 That didn't work as well.那也没有用。

I have a feeling you should be able to do such a thing.我有一种感觉,你应该能够做这样的事情。 I know date parses the date just fine.我知道 date 可以很好地解析日期。 The format is something like 'Thu Aug 11 11:40:00 UTC 2023'.格式类似于“2023 年 8 月 11 日星期四 11:40:00 UTC 2023”。

Is there any way to do this in awk?在 awk 中有什么方法可以做到这一点吗? I've gone through a lot of documentation without ever seeing an example of fields being processed in a shell command.我浏览了很多文档,却没有看到在 shell 命令中处理的字段示例。

Use string concatenation.使用字符串连接。

You also need quotes around the --date argument, since it contains whitespce.'您还需要在--date参数周围加上引号,因为它包含 whitespce。

command = "date --date=\"" $4 "\" +%s"
command | getline DUE
close(command)
command2 = "date +%s"
command2 | getline CURR
close(command2)

side note about date utility::: the syntax is really different between gnu/linux one and BSD ones:关于date实用程序的旁注::: gnu/linuxBSD之间的语法确实不同:

  • gnu one allows for fractional epochs for input and output gnu一允许输入和 output 的小数时期
  • the @ is a mandatory requirement for epochs @是时代的强制性要求
gdate -d '@16602518201915245' # GNU-date (GNU coreutils 9.1)
Mon Nov  8 22:07:25 EST 526114827
  • BSD one won't accept @ or non-integers BSD 不接受@或非整数
 date -r 16602518201915245 # BSD-date (from FreeBSD 12.0)
Mon Nov  8 22:07:25 EST 526114827

they do share one common feature though:不过,它们确实有一个共同特征:

  • an upper-limit for the year -1 + 2 ^ ( 3 ^ 3 + 4 )年份的上限-1 + 2 ^ ( 3 ^ 3 + 4 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM