user1306777
user1306777

Reputation: 489

How to split string on forward slash in bash

example String :

/gasg/string

expected result : string

Characters to to remove: all characters between the "/" symbols including the symbols

Upvotes: 34

Views: 60571

Answers (3)

pizza
pizza

Reputation: 7640

you can use bash string manipulation

a='/gasg/string'
echo ${a##*/}

Upvotes: 11

Hristo Iliev
Hristo Iliev

Reputation: 74455

With sed:

$ echo "/gasg/string" | sed -e 's/\/.*\///g'
string

With buil-in bash string manipulation:

$ s="/gag/string"
$ echo "${s##/*/}"
string

Your strings look exactly like Unix pathnames. That's why you could also use the basename utility - it returnes the last portion of the given Unix pathname:

$ basename "/gag/string"
string
# It works with relative paths and spaces too:
$ basename "gag/fas das/string bla bla"
string bla bla

Upvotes: 35

Maria Zverina
Maria Zverina

Reputation: 11173

Also awk - use slash as separator and print last field

echo "/gas/string" | awk -F/ '{print $NF}'

Or cut - but that will only work if you have same number of directories to strip

echo "/gasg/string" |cut -d/ -f 3

Upvotes: 46

Related Questions