shell脚本从正斜杠分隔的变量中提取文本 [英] shell script to extract text from a variable separated by forward slashes
问题描述
我正在尝试找到一种方法来从变量中提取文本,并用正斜杠分隔单词.我尝试使用cut
进行尝试,所以这是一个示例:
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'
说,我只想从中提取three
,
cut -d/ -f3 <<<"${variable}"
但这似乎行不通.关于我在做什么错的任何想法吗?还是有一种使用AWK做到这一点的方法?
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?
推荐答案
在分配字符串或变量期间,您需要删除=
之前和之后的空格.并告诉cut命令打印第四个字段.
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
使用定界符/
,cut命令将输入分割为类似的内容.
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.
这篇关于shell脚本从正斜杠分隔的变量中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!