问题描述:

I'm looking to get 1.2.3.4 of string 1.2.3.4.5

I know that I can use this code to get the final number, but what can I use to get all numbers previous. (Including ':')

$ foo=1.2.3.4.5

$ c_num=`echo ${foo##*.}`

$ echo $c_num

$ 5

I have tried using IFS.

$ IFS='.' read -ra STRING <<< "$foo"

$ u_num="${STRING[0]}"'.'"${STRING[1]}"'.'"${STRING[2]}"'.'"${STRING[3]}"

$ echo $u_num

$ 1 2 3 4

# It should have returned 1.2.3.4

网友答案:

Try using:

echo ${foo%.*}

Yielding:

foo="1.2.3.4.5"
echo ${foo%.*}
1.2.3.4

and

foo="1 2 6"
echo ${foo%.*}

yields

1 2 6

If you want to convert the spaces to ., you can use tr:

echo $foo | tr ' ' '.'

Yielding the following for foo="1 2 6"

1.2.6
相关阅读:
Top