在jq的输出中插入破折号到特定位置。

huangapple go评论63阅读模式
英文:

Insert dash into the output of jq at specific positions

问题

You can modify your jq code like this to change the date format:

echo '{ "date":"20200101" }{ "date":"20210101" }' | jq -r '"The bus will be here on \(.date | strptime("%Y%m%d") | strftime("%Y-%m-%d")), at ten o clock"'

This code uses strptime to parse the input date in the format "20200101" and then strftime to format it as "2020-01-01" in the output.

英文:

How do I modify the jq code in:

echo '{"date":"20200101"}{"date":"20210101"}' | jq -r '"The bus will be here on \( .date ), at ten o clock"'

to change the format of the date from eg 20200101 into 2020-01-01?

I get the output:

The bus will be here on 20200101, at ten o clock
The bus will be here on 20210101, at ten o clock

I want the output:

The bus will be here on 2020-01-01, at ten o clock
The bus will be here on 2021-01-01, at ten o clock

I tried:

echo '{"date":"20200101"}{"date":"20210101"}' | jq -r '"The bus will be here on \( .date | strftime("%Y-%m-%d") ), at ten o clock"'

but that tells me:

jq: error (at <stdin>:1): strftime/1 requires parsed datetime inputs

strftime apparently needs the input date to be in another format.

答案1

得分: 2

根据文档strftime 的格式如下:

strptimestrftime 的格式字符串在典型的 C 库文档中有描述。ISO 8601 日期时间的格式字符串为 "%Y-%m-%dT%H:%M:%SZ"。

这就是为什么您的表达式出现错误,因为输入与所需格式不匹配。

在这种情况下,您应该简单地切分字符串:

echo '{ "date":"20200101"}{ "date":"20210101"}' | jq -r '"The bus will be here on \( .date | .[0:4] + "-" + .[4:6] + "-" + .[6:8] ), at ten o clock"'
英文:

According to the docs, the format for strftime is:

> The format strings for strptime and strftime are described in typical C library documentation. The format string for ISO 8601 datetime is "%Y-%m-%dT%H:%M:%SZ".

which is why your expression errors, since the input does not match the required format.

In this case, you should simply slice the string:

echo '{"date":"20200101"}{"date":"20210101"}' | jq -r '"The bus will be here on \( .date | .[0:4] + "-" + .[4:6] + "-" + .[6:8] ), at ten o clock"'

答案2

得分: 2

你还可以使用strptime首先解析%Y%m%d格式的日期,然后使用strftime重新格式化它,例如%F

… | jq -r '"The bus will be here on \(.date | strptime("%Y%m%d") | strftime("%F")), at ten o clock"'
The bus will be here on 2020-01-01, at ten o clock
The bus will be here on 2021-01-01, at ten o clock

演示

英文:

You can also use strptime to first parse the %Y%m%d-formatted date, then re-format it with strftime to, for example, %F:

… | jq -r '"The bus will be here on \(.date | strptime("%Y%m%d") | strftime("%F")), at ten o clock"'
The bus will be here on 2020-01-01, at ten o clock
The bus will be here on 2021-01-01, at ten o clock

Demo

huangapple
  • 本文由 发表于 2023年5月17日 22:43:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273350.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定