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

妖精的绣舞 提交于 2019-12-02 15:19:23

问题


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?


回答1:


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.




回答2:


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

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



回答3:


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' 


来源:https://stackoverflow.com/questions/26758110/shell-script-to-extract-text-from-a-variable-separated-by-forward-slashes

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