如何在字符串的开头提取部分?

时间:2013-07-30 13:36:16

标签: linux string bash shell sh

我有字符串包含路径

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

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

如何使用字符串操作?而不是sed,awk,grep ...


字符串操作示例:

tmp="${string#toto.titi.tata.*.}"
num1="${tmp%abc*}"

2 个答案:

答案 0 :(得分:0)

不幸的是,除非您愿意使用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或其他一些实用程序。

答案 1 :(得分:0)

好的...... splitsubstring就是答案。

string [] array = "toto.titi.tata.2.abc.def".split('.');
array[0]+array[1] ="toto.titi";

"toto.titi.tata.2.abc.def".substring(0,10);
相关问题