user2043160
user2043160

Reputation: 21

shell script to extract text from a variable separated by forward slashes

I am trying to find a way to to extract text from a variable with words separated by a forward slash. I attempted it using cut, so here's an example:

set variable = '/one/two/three/four'  

Say I just want to extract three from this, I used:

cut -d/ -f3 <<<"${variable}"

But this seems to not work. Any ideas of what I'm doing wrong? Or is there a way of using AWK to do this?

Upvotes: 0

Views: 1213

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174874

You need to remove the spaces before and after to = during string or variable assignment. And tell the cut command to print the 4th field.

$ variable='/one/two/three/four'
$ cut -d/ -f4 <<<"${variable}"
three

With the delimiter /, cut command splits the input like.

             /one/two/three/four
            |  |   |    |    |
            1  2   3    4    5

that is, when it splits on first slash , you get an empty string as first column.

Upvotes: 2

Jotne
Jotne

Reputation: 41460

Here is an awk version:

awk -F\/ '{print $4}' <<< "$variable"
three

or

echo "$variable" | awk -F\/ '{print $4}'
three

PS to set a variable not need for set and remove spaces around =

variable='/one/two/three/four' 

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74705

I think that the main problem here is in your assignment. Try this:

var='/one/two/three/four'
cut -d/ -f4 <<<"$var"

Upvotes: 1

Related Questions