Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String in Unix Shell Script

Tags:

shell

unix

I have a String like this

//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf 

and want to get last part of

00000000957481f9-08d035805a5c94bf
like image 740
user3348567 Avatar asked Feb 24 '14 21:02

user3348567


4 Answers

Let's say you have

text="//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf"

If you know the position, i.e. in this case the 9th, you can go with

echo "$text" | cut -d'/' -f9

However, if this is dynamic and your want to split at "/", it's safer to go with:

echo "${text##*/}"

This removes everything from the beginning to the last occurrence of "/" and should be the shortest form to do it.

For more information on this see: Bash Reference manual

For more information on cut see: cut man page

like image 57
Karsten S. Avatar answered Oct 14 '22 07:10

Karsten S.


The tool basename does exactly that:

$ basename //ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf  
00000000957481f9-08d035805a5c94bf
like image 28
Chris Seymour Avatar answered Oct 14 '22 08:10

Chris Seymour


I would use bash string function:

$ string="//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf"

$ echo "${string##*/}"
00000000957481f9-08d035805a5c94bf

But following are some other options:

$ awk -F'/' '$0=$NF' <<< "$string"
00000000957481f9-08d035805a5c94bf

$ sed 's#.*/##g' <<< "$string"
00000000957481f9-08d035805a5c94bf

Note: <<< is herestring notation. They do not create a subshell, however, they are NOT portable to POSIX sh (as implemented by shells such as ash or dash).

like image 36
jaypal singh Avatar answered Oct 14 '22 06:10

jaypal singh


You can use this BASH regex:

s='//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf'
[[ "$s" =~ [^/]+$ ]] && echo "${BASH_REMATCH[0]}"
00000000957481f9-08d035805a5c94bf
like image 33
anubhava Avatar answered Oct 14 '22 06:10

anubhava