bash awk:将日期字符串从 YYYYMMDD 格式化为 YYYY-MM-DD

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22472385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:57:05  来源:igfitidea点击:

awk: format date string from YYYYMMDD to YYYY-MM-DD

linuxstringbashawkformat

提问by Manuel Weitzel

I have a CSVfile which I parse using awkbecause I don't need all columns. The problem I have is that one column is a date but in the format YYYYMMDDbut I need it in YYYY-MM-DDand I don't know how to achieve that.

我有一个CSV要解析的文件,awk因为我不需要所有列。我遇到的问题是,一列是日期,但采用了格式,YYYYMMDD但我需要它,但我YYYY-MM-DD不知道如何实现。

I already tried with split($27, a)but it doesn't split it - so a[0]returns the whole string.

我已经尝试过,split($27, a)但它没有拆分它 - 所以a[0]返回整个字符串。

回答by devnull

You could use substr:

你可以使用substr

printf "%s-%s-%s", substr(,0,4), substr(,5,2), substr(,7,2)

Assuming that the 27thfield was 20140318, this would produce 2014-03-18.

假设第 27字段是20140318,这将产生2014-03-18

回答by Khanjarrr

Use your awkoutput as input to date -d, e.g.

使用您的awk输出作为输入date -d,例如

$ date -d 20140918 +'%Y-%m-%d'
2014-09-18