gpt4 book ai didi

linux - 如何提取字符串开头的一部分?

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

这个问题在这里已经有了答案:





How to extract a part of string?

(7 个回答)


8年前关闭。




我有字符串包含一个路径

string="toto.titi.tata.2.abc.def"

我只想提取 2 第一个路径名。所以对于上面的例子,我想提取 toto.titi从字符串。

如何用字符串操作做到这一点?而不是 sed、awk、grep...

字符串操作示例:
tmp="${string#toto.titi.tata.*.}"
num1="${tmp%abc*}"

最佳答案

不幸的是,除非你愿意使用 eval ,我认为你需要使用一个中间变量:

s=${string#*.}  # Remove the first component
echo ${s#*.} # Remove the second

这给出了删除前两个组件的字符串的值。如果你想保留它们,你可以这样做:
# Remove one component at a time while there are more than two
while echo $string | grep -q '\..*\.'; do string=${string%.*}; done

但实际上,您最好使用 sed或其他一些实用程序。

关于linux - 如何提取字符串开头的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17948606/

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