How to extract a part of string?

半城伤御伤魂 提交于 2019-12-11 15:47:45

问题


I have string contains a path

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

I want to extract the substring which is situated after toto.titi.1.tata.2.. but 1 and 2 here are examples and could be other numbers.

In general: I want to extract the substring which situated after toto.titi.[i].tata.[j]..

[i] and [j] are a numbers

How to do it?


回答1:


You can use cut

 echo $string | cut -f6- -d'.'



回答2:


Pure bash solution:

[[ $string =~ toto\.titi\.[0-9]+\.tata\.[0-9]+\.(.*$) ]] && result="${BASH_REMATCH[1]}"
echo "$result"



回答3:


An alternate bash solution that uses parameter expansion instead of a regular expression:

echo "${string#toto.titi.[0-9].tata.[0-9].}"

If the numbers can be multi-digit values (i.e., greater than 9), you would need to use an extended pattern:

shopt -s extglob
echo "${string#toto.titi.+([0-9]).tata.+([0-9]).}"



回答4:


This does it:

echo ${string} | sed -re 's/^toto\.titi\.[[:digit:]]+\.tata\.[[:digit:]]+\.//'



回答5:


May be like this:

echo "$string" | cut -d '.' -f 6-




回答6:


You can use sed. Like this:

string="toto.titi.1.tata.2.abc.def"
string=$(sed 's/toto\.titi\.[0-9]\.tata\.[0-9]\.//' <<< "$string")
echo "$string"

Output:

abc.def



回答7:


try this awk line:

awk -F'toto\\.titi\\.[0-9]+\\.tata\\.[0-9]+\\.' '{print $2}' file

with your example:

kent$  echo "toto.titi.1.tata.2.abc.def"|awk -F'toto\\.titi\\.[0-9]+\\.tata\\.[0-9]+\\.' '{print $2}'
abc.def


来源:https://stackoverflow.com/questions/17812158/how-to-extract-a-part-of-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!