我想要查看句子的某些部分,例如:/hana/new/register
。在这里我需要grep /
字符之间的第一个元素,所以在这里我想得到hana
。
我怎么能在shell中做到这一点?
您可以使用sed
并使用字符类和后引用捕获第一个/.../
之间的任何内容。例如:
echo '/samarth/new/register' | sed 's/^\/\([^/]*\).*$/\1/'
samarth
sed
命令是sed 's/find/replace/'
形式的基本替代命令,在第一个/
(逃脱为\/
)之后找到所有内容并用^
锚定到开头。你使用一个捕获组\(...\)
来捕获字符类[^/]*
(一切都不是/
),在替换的替换方面,你使用反向引用\1
将你最初捕获的内容作为替换。
要获得斜线分隔线上的第一个单词,我们可以使用cut
:
$ echo '/samarth/new/register then i want to grep samarth' | cut -d/ -f 2
samarth
$ echo '/hana/new/register' | cut -d/ -f 2
hana
或者,我们可以使用awk
:
$ echo '/samarth/new/register then i want to grep samarth' | awk -F/ '{print $2}'
samarth
$ echo '/hana/new/register' | awk -F/ '{print $2}'
hana