问题
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