简体   繁体   English

使用 awk 或 sed 从 bash 变量中提取动态信息的正则表达式

[英]Regexp extract of the dynamic information from the bash variable using awk or sed

If the value changes, ie it could be如果值发生变化,即它可能是

project-crm-backend-build-pipeline-run-98b6r-slack-notific-8fzvf

or或者

backend-build-pipeline-run-aaaaa-test-eeee

and I only need to extract the following from both examples above我只需要从上面的两个例子中提取以下内容

project-crm-backend-build-pipeline-run-98b6r
backend-build-pipeline-run-aaaaa

ie the only thing that is constant is "pipeline-run", everything else could be changing, so I need to include everything before the pipeline-run and the single token right after the pipeline-run即唯一不变的是“管道运行”,其他一切都可能发生变化,所以我需要在管道运行之前包含所有内容,并在管道运行之后包含单个令牌

With Parameter Expansion :参数扩展

$ t='build-pipeline'

$ s='project-crm-backend-build-pipeline-run-98b6r-slack-notific-8fzvf'
$ echo "${s%-${s#*${t}-*-*-}}"
project-crm-backend-build-pipeline-run-98b6r

$ s='backend-build-pipeline-run-aaaaa-test-eeee'
$ echo "${s%-${s#*${t}-*-*-}}"
backend-build-pipeline-run-aaaaa

${s#*${t}-*-*-} will delete minimally from start of string, matching contents of variable t and then till 3rd - after. ${s#*${t}-*-*-}将从字符串的开头至少删除,匹配变量t的内容,然后直到第 3 个-之后。

The remaining string that is obtained is then used (after prefixing with a - character) to be deleted from end of string, thus giving the portion required.然后使用获得的剩余字符串(在以-字符为前缀之后)从字符串末尾删除,从而提供所需的部分。


With sedsed

echo "$s" | sed -E 's/('"$t"'-run-[^-]+).*/\1/'

Both these solution assume contents of variable t don't have characters that can effect the expansion/regex.这两种解决方案都假设变量t的内容没有可以影响扩展/正则表达式的字符。

okay this is my working solution, just in case someone gets into the same issue好的,这是我的工作解决方案,以防万一有人遇到同样的问题

TEKTON_PIPELINE_NAME=build-pipeline
echo $POD_NAME | awk -v search="[0-9a-zA-Z-]+$TEKTON_PIPELINE_NAME-run-[a-z0-9]+" 'match($0, search) { print substr( $0, RSTART, RLENGTH )}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM