如何在Bash Shell中将普通文本转换为日期格式?

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

How to convert normal text into date format in bash shell?

问题

将其从

格式1:12272019(这只是一个数字)

转换为

格式2:2019-12-27

我尝试使用以下方法:
date -d '12272019' +%Y-%m-%d

但它显示无效的日期格式。

英文:

I want to convert it from

Format 1: 12272019(this is just a number)

To

Format 2: 2019-12-27

I tried using below:
date -d '12272019' +%Y-%m-%d

But it is showing invalid date format

答案1

得分: 3

The date command only accepts a predefined set of formats for its input. Your format mmddyyyy is not part of that set.

You can re-arrange your date string manually using either sed:

sed -E 's/(..)(..)(....)/--/' <<< 12272019

or bash:

date=12272019
echo "${date:4}-${date:0:2}-${date:2:2}"
英文:

The date command only accepts a predefined set of formats for its input. Your format mmddyyyy is not part of that set.

You can re-arrange your date string manually using either sed:

sed -E &#39;s/(..)(..)(....)/--/&#39; &lt;&lt;&lt; 12272019

or bash:

date=12272019
echo &quot;${date:4}-${date:0:2}-${date:2:2}&quot;

答案2

得分: 0

在OS/X上,date有一些不同之处,因此您可以为date指定输入格式:

date -jf "%m%d%Y" 12272019 +"%Y-%m-%d"
# => 2019-12-27

然而,Linux不允许您这样做,但您可以使用sed轻松实现:

echo 12272019 | sed -e 's/\(..\)\(..\)\(....\)/--/'
# => 2019-12-27
英文:

On OS/X, date is quite a bit different, so you can specify the input format for date:

date -jf &quot;%m%d%Y&quot; 12272019 +&quot;%Y-%m-%d&quot;
# =&gt; 2019-12-27

Linux does not allow you to do that though, but you can do it easily with sed:

echo 12272019 | sed -e &#39;s/\(..\)\(..\)\(....\)/--/&#39;
# =&gt; 2019-12-27

huangapple
  • 本文由 发表于 2020年1月6日 16:22:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608794.html
匿名

发表评论

匿名网友

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

确定