使用 Cut delimiter 提取字符串的初始部分

Use Cut delimiter to extract initial part of the string

我有一个变量 A,其值的第一部分始终为 DEV-UI。 A 的各种可能值可能是:DEV-UIDEV-UI2DEV-UI*

我只想从中提取 DEV 并将其存储在另一个变量中。这样,另一个变量 B 的值总是 DEV.

如何从A中提取DEV并存储在B中?

我正在寻找任何剪切定界符或任何可用于在我的 shell 脚本中实现此目的的表达式。

B=$(echo "$A" | cut -d'-' -f1)

将字符串拆分为 - 和 returns 第一部分。

明显的步骤显然只是设置 B="DEV",因为您声明它始终是 DEV。但是,下面我将展示如何将其提取为第一个字段。

这在一定程度上取决于您拥有的 shell 类型,但如果它是任何形式的 sh-compatible shell 您可以:

$ B=${A%%-*}

这在POSIX shell command language中有解释:

${parameter%%[word]} Remove Largest Suffix Pattern. The word shall be expanded to produce a pattern. The parameter expansion shall then result in parameter, with the largest portion of the suffix matched by the pattern deleted.

$ A="hello-big-world"
$ echo ${A%-*}
hello-big
$ echo ${A%%-*}
hello

当使用 C Shell 时,你就没那么幸运了:

% set a = "hello-big-world"
% set b = `echo $a | cut -d- -f1`
% echo $b
hello