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

穿精又带淫゛_ 提交于 2019-12-02 11:23:53

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.

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

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

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