Shell - 我怎么能在一个句子中写一个特定的单词?

问题描述 投票:-2回答:2

我想要查看句子的某些部分,例如:/hana/new/register。在这里我需要grep /字符之间的第一个元素,所以在这里我想得到hana

我怎么能在shell中做到这一点?

shell grep words
2个回答
1
投票

您可以使用sed并使用字符类和后引用捕获第一个/.../之间的任何内容。例如:

echo '/samarth/new/register' | sed 's/^\/\([^/]*\).*$/\1/'
samarth

sed命令是sed 's/find/replace/'形式的基本替代命令,在第一个/(逃脱为\/)之后找到所有内容并用^锚定到开头。你使用一个捕获组\(...\)来捕获字符类[^/]*(一切都不是/),在替换的替换方面,你使用反向引用\1将你最初捕获的内容作为替换。


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
© www.soinside.com 2019 - 2024. All rights reserved.