gpt4 book ai didi

linux - 剥离单词并找到它的长度

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:09 25 4
gpt4 key购买 nike

我是 Linux 新手。

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

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

sstripfirstword = awk '{print substr($0,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"

请注意 = 字符周围没有空格。

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

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

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

输出

abc

魔术发生在 shell 中的参数修改功能

echo ${var%%-*} 

意思是“从变量值的右边往回匹配,匹配-*的最长字符串”(使用shell reg ex,其中*等同于大多数语言的正则表达式 .*)。

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

健康教育

关于linux - 剥离单词并找到它的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57717183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com