在未知字符分隔同一行匹配,更换一个模式多次 [英] match and replace one pattern multiple times in the same line delimited by unknown characters
问题描述
鉴于形式的输入:
select * from foo where ts>@(-2 days) and ts < @(-1 hour)
(这当然只是一个例子,我想支持任何查询,构造和@任前pression())
(this is of course just an example. I want to support any query construct and any expression in @())
我要替换的前pression每 @()
与评估的结果日期--date = EXP +%小号
,其中EXP是前pression(所以其结果将是
I want to replace the expression in every @()
with the result of evaluating date --date=exp +%s
, where 'exp' is the expression (so in the example above the result will be
select * from foo where ts>1436694136 and ts < 1436863336
更一般地,我怎么从模式调用一个shell命令捕获作为参数的结果替代的模式?
More generally, how do I replace a pattern with the result of invoking a shell command with captures from the pattern as arguments?
(我标记用Perl和bash的问题,但我开到任何东西)
(I've tagged the question with perl, and bash, but am open to anything)
推荐答案
使用GNU sed的:
Using gnu sed:
$ sql_expr="select * from foo where ts>@(-2 days) and ts < @(-1 hour)"
$ sed -r 's|@\(([^)]*)\)|$(date +%s --date "now\1")|g; s|.*|echo "&"|e' <<< "$sql_expr"
Gave:
select * from foo where ts>1436696209 and ts < 1436865409
请注意,这code假定的@内容(...)
是有效的前pressions,日期计算。
Note that this code assumes that the contents of @(...)
are valid expressions, for date calculations.
说明:
- 第一八佰伴pression将取代所有
@()
出现与$(日期+%S --date现在_ex pression _)
,其中_ex pression _
将是类似-2天
。 - 二取代前pression增加
回声...
围绕整个字符串&安培;的执行的生成线。您可以删除E在第二前pression
标志,以找出什么命令得到真正执行。
- First expression will replace all
@()
occurrences with$(date +%s --date "now _expression_")
where_expression_
is going to be something like-2 days
. - Second replace expression adds
echo "..."
around entire string & executes the generated line. You can remove thee
flag in second expression to find out what command gets executed actually.
这篇关于在未知字符分隔同一行匹配,更换一个模式多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!