如何在 shell 中使用 sed 或 grep 提取字符串中前 2 个破折号之间的文本



我有这样的字符串feature/test-111-test-test. 我需要提取字符串直到第二个破折号,并将正斜杠更改为破折号。

我必须使用 shell 语法在 Makefile 中执行此操作,对我来说不起作用一些可以提供帮助的正则表达式或这种情况

最后我必须得到这样的 smth:
input -feature/test-111-test-test<</strong>br/>output -feature-test-111-或至少feature-test-111

feature/test-111-test-test | grep -oP 'A(?:[^-]++-??){2}' | sed -e 's///-/g')

但是grep -oP在我的情况下不起作用。这个正则表达式也不起作用 -(.*?-.*?)-.*.

另一个使用捕获组和正则表达式/模式迭代的sed解决方案(与 Socowi 使用的相同):

$ s='feature/test-111-test-test'
$ sed -E 's///-/;s/^(([^-]*-){3}).*$/1/' <<< "${s}"
feature-test-111-

哪里:

  • -E- 启用扩展正则表达式支持
  • s///-/- 将/替换为-
  • s/^....*$/- 匹配输入行的起点和终点
  • (([^-]-){3})- 捕获组 #1,由 3 组anything not -组成,后跟-
  • 1- 仅打印捕获组 #1(这将丢弃不属于捕获组的行上的其他所有内容)

将结果存储在变量中:

$ url=$(sed -E 's///-/;s/^(([^-]*-){3}).*$/1/' <<< "${s}")
$ echo $url
feature-test-111-

您可以使用awk记住,在Makefile中,awk命令中的$字符必须加倍:

url=$(shell echo 'feature/test-111-test-test' | awk -F'-' '{gsub(///, "-", $$1);print $$1"-"$$2"-"}')
echo "$url"
# => feature-test-111-

请参阅在线演示。在这里,-F'-'将字段分隔符设置为-gsub(///, "-", $1)字段 1 中将/替换为-print $1"-"$2"-"打印-分隔字段 1 和 2 的值。

或者,使用正则表达式作为字段分隔符:

url=$(shell echo 'feature/test-111-test-test' | awk -F'[-/]' '{print $$1"-"$$2"-"$$3"-"}')
echo "$url"
# => feature-test-111-

-F'[-/]'选项将字段分隔符设置为-/

'{print $1"-"$2"-"$3"-"}'部分打印带有分隔连字符的第一个、第二个和第三个值。

请参阅在线演示。

要获得字符C的第n次出现,您不需要花哨的perl正则表达式。相反,构建一个形式的正则表达式">(任何不C,然后C)n次">

grep -Eo '([^-]*-){2}' | tr / - 

带有sedcut

echo feature/test-111-test-test| cut -d'-' -f-2 |sed 's///-/'

输出

feature-test-111
<小时 />
echo feature/test-111-test-test| cut -d'-' -f-2 |sed 's///-/;s/$/-/'

输出

feature-test-111-

您可以使用简单的 BRE 正则表达式形式,而不是某种东西,那么[^-]*-的东西来获取除-之外的所有字符,直到一个-

这有效:

echo 'feature/test-111-test-test' | sed -nE 's/^([^/]*)/([^-]*-[^-]*-).*/1-2/p'
feature-test-111-

使用参数扩展/替换的另一个想法:

s='feature/test-111-test-test'
tail="${s////-}"                   # replace '/' with '-'
# split first field from rest of fields ('-' delimited); do this 3x times
head="${tail%%-*}"                  # pull first field
tail="${tail#*-}"                   # drop first field
head="${head}-${tail%%-*}"          # pull first field; append to previous field
tail="${tail#*-}"                   # drop first field
head="${head}-${tail%%-*}-"         # pull first field; append to previous fields; add trailing '-'
$ echo "${head}"
feature-test-111-

一个简短的 sed 解决方案,没有扩展的正则表达式:

sed 's|(.*)/([^-]*-[^-]*).*|1-2|'

相关内容

最新更新