簡體   English   中英

如何使用 shell 中的 sed 或 grep 提取字符串中前兩個破折號之間的文本

[英]How to extract text between first 2 dashes in the string using sed or grep in shell

我有這樣的字符串feature/test-111-test-test 我需要提取字符串直到第二個破折號並將正斜杠更改為破折號。

我必須在 Makefile 中使用 shell 語法來做這件事,對我來說,一些正則表達式不起作用,或者這種情況下

最后我必須得到這樣的東西:
輸入 - feature/test-111-test-test
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命令中的$ char必須加倍

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/\//-/'

Output

feature-test-111

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

Output

feature-test-111-

您可以使用not something 的簡單 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|'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM