剥离单词并找到它的长度

Strip the word and find its length

我是 linux 的新手。

我想从abc-d023-1234中获取单词abc并获取剥离单词的长度(abc)

$serverenvicheck =abc-d023-1234
stripfirstword= 'echo  $serverenvicheck | cut -d '-' f -1'

sstripfirstword = awk '{print substr([=10=],1,4)|' $stripfirstword

输出

./test.sh: line 23: echo  $serverenvicheck | cut -d - f -1: command not found
./test.sh: line 25: sstripfirstword: command not found
stripped firstword 

如何去除单词以及找到它的长度?

./test.sh: line 23: echo  $serverenvicheck | cut -d - f -1: command not found
./test.sh: line 25: stripfirstword: command not found

shell 脚本中的变量赋值采用

的形式
var="some values"

请注意 = 字符周围没有 space。

解决您问题的最有效方法是

serverenvicheck="abc-d023-1234"
stripfirstword="${serverenvicheck%%-*}"
echo "$stripfirstword"

echo  "length of $stripfirstword 's value is ${#stripfirstword}"

输出

abc

奇迹发生在

中的shell参数修改功能
echo ${var%%-*} 

表示 "match back from the right side of the variable value, the longest string that matches -*"(使用 shell 正则表达式,其中 * 等同于大多数语言的正则表达式 .*)。

如果你使用 echo ${var%-*} 你将从右边开始匹配最短的匹配,在你的情况下你会得到 abc-d023.

IHTH