user3348567
user3348567

Reputation: 99

Split String in Unix Shell Script

I have a String like this

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

and want to get last part of

00000000957481f9-08d035805a5c94bf

Upvotes: 8

Views: 39663

Answers (7)

Karsten S.
Karsten S.

Reputation: 2391

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

Upvotes: 21

Tilo
Tilo

Reputation: 33732

In case you want more than just the last part of the path, you could do something like this:

  echo $PWD | rev | cut -d'/' -f1-2 | rev

Upvotes: 3

Bibhu Prasad Behera
Bibhu Prasad Behera

Reputation: 1

You can try this...

echo //ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf |awk -F "/" '{print $NF}'

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77095

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).

Upvotes: 2

user1461760
user1461760

Reputation:

This can be done easily in awk:

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

echo "${string}" | awk -v FS="/" '{ print $NF }'

Use "/" as field separator and print the last field.

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85785

The tool basename does exactly that:

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

Upvotes: 7

anubhava
anubhava

Reputation: 785108

You can use this BASH regex:

s='//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf'
[[ "$s" =~ [^/]+$ ]] && echo "${BASH_REMATCH[0]}"
00000000957481f9-08d035805a5c94bf

Upvotes: 1

Related Questions