如何更改sed中的日期格式? [英] How to change date format in sed?
问题描述
假设我想通过 date
命令将时间戳中的日期转换为另一种格式.在控制台中,我会说 date -d@
但我碰巧想对文本文件中的许多字段执行此操作.
Say I want to convert a date in timestamp to another format through the date
command. In console I would say date -d@<timestamp>
but I happen to want to do this to many fields in a text file.
使用 e
在 sed
中执行(sed (GNU sed) 4.2.2
,实际上)我是说:
Using the e
to execute in sed
(sed (GNU sed) 4.2.2
, actually) I am saying:
$ echo 1449158360 | sed -r 's#.*([0-9]{10}).*#date -d@1 "+%Y";#e'
2015
效果很好,不错!
现在我创建了一个虚拟文件myfile
:
Now I created a dummy file myfile
:
my timestamp is 1449158360 but also I wonder what date was 1359199960.
我想将其替换为相同但具有时间戳的相对年份:
Which I would like to have replaced to the same but having the relative year of the timestamps:
my timestamp is 2015 but also I wonder what date was 2013.
但是,如果我尝试运行与上面相同的命令,则会失败:
However, if I try to run the same command as above it fails:
$ sed -r 's#([0-9]{10})#date -d@"1" "+%Y";#e' myfile
sh: my: command not found
sh: but: command not found
因为 sed
将第一个单词解释为要执行的内容.
Because sed
interprets the first words as something to execute.
显然,如果我只获取这些数据而没有其他任何东西,它就可以工作:
Obviously it works if I just fetch these data and nothing else:
$ sed -r 's#.*([0-9]{10}).*#date -d@"1" "+%Y";#ge' myfile
2015
所以我想知道:我应该怎么做才能针对 sed
中捕获的组调用 date
并用它替换文本,考虑到它被其他必须保留的文本包围原封不动?
So I wonder: what should I do to call date
against captured groups in sed
and replace text with it, considering it is surrounded by other text that have to remain untouched?
推荐答案
e
switch in sed
替换应用 sh -c
到不匹配的文本以及从这个命令明显:
e
switch in sed
substitute applies sh -c
to unmatched text as well as evident from this command:
echo 'a 1449158360' | sed -r 's#([0-9]{10})#date -d@1 "+%Y";#e'
sh: a: command not found
所以即使我们只匹配 1449158360
但 sh -c
正在 a 1449158360
上运行.
So even though we are matching only 1449158360
but sh -c
is being run on a 1449158360
.
由于 sed
中没有非贪婪和前瞻正则表达式,这个解决方法正则表达式可能看起来很疯狂,但这就是您如何像您的问题一样为来自文件的多个匹配输入运行它:
Due to absence of non-greedy and lookaheads regex in sed
this workaround regex might appear crazy but this is how you can run it for multiple matching input from file as in your question:
sed -r 's#(([^0-9][0-9]{0,9})*)([0-9]{10})(([0-9]{0,9}[^0-9])*)#printf "%s%s%s" "1" $(date -d@3 "+%Y") "4";#ge' file
基本上我们在这个正则表达式中匹配
.
Basically we are matching <before>10-digits<after>
in this regex.
输出:
my timestamp is 2015 but also I wonder what date was 2013.
为了阐明所使用的正则表达式,我创建了这个演示.
To clarify the regex used I have created this demo.
这绝不是 e
模式问题的通用解决方案,请将其视为基于正则表达式的解决方法.
By no means this is a generic solution to e
mode issue, treat it as a regex based workaround.
这篇关于如何更改sed中的日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!