击败SED替换为第一次驱动到右

发布于 2025-02-13 01:38:40 字数 179 浏览 2 评论 0原文

我试图在之前获得第一个单词/

我正在使用以下sed:

echo 'a/b/c' | sed 's/\(.*\)\/\(.*\)/\1/g'

但是这给了我a/b,我希望它只给我a

有什么想法吗?

I am trying to obtain the first word before /

I am using following sed:

echo 'a/b/c' | sed 's/\(.*\)\/\(.*\)/\1/g'

But this gives me a/b, I would like it to give me only a

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浅忆 2025-02-20 01:38:40

您可以使用

echo 'a/b/c' | sed 's,\([^/]*\)/.*,\1,'

详细信息

  • \([^/]*\) - 组1(\ 1): /
  • / - a / char
  • 。* - 字符串的其余部分。

或者,如果您有变量,则可以使用字符串操作:

s='a/b/c'
echo "${s%%/*}"
# => a

在此,%%从末端删除最长的子字符串,与/* glob模式匹配,直到字符串中的第一个/

You can use

echo 'a/b/c' | sed 's,\([^/]*\)/.*,\1,'

Details:

  • \([^/]*\) - Group 1 (\1): any zero or more chars other than /
  • / - a / char
  • .* - the rest of the string.

Or, if you have a variable, you can use string manipulation:

s='a/b/c'
echo "${s%%/*}"
# => a

Here, %% removes the longest substring from the end, that matches the /* glob pattern, up to the first / in the string including it.

呆头 2025-02-20 01:38:40

可以在bash本身中轻松完成此操作,而无需调用任何外部实用程序:

s='a/b/c'
echo "${s%%/*}"

a

# or else
echo "${s/\/*}"

a

This can be done easily in bash itself without calling any external utility:

s='a/b/c'
echo "${s%%/*}"

a

# or else
echo "${s/\/*}"

a
水晶透心 2025-02-20 01:38:40

使用sed和替代定界符,以防止与数据中的类似字符发生冲突。

$ echo 'a/b/c' | sed 's#/.*##'
a

Using sed and an alternate delimiter to prevent a conflict with a similar char in the data.

$ echo 'a/b/c' | sed 's#/.*##'
a
眼眸 2025-02-20 01:38:40

使用剪切而不是sed以隔离char分离字段,以清晰,简单和效率:

$ echo 'a/b/c' | cut -d'/' -f1
a

$ echo 'a/b/c/d/e/f/g/h/i' | cut -d'/' -f5
e

Use cut instead of sed to isolate char-separated fields for clarity, simplicity, and efficiency:

$ echo 'a/b/c' | cut -d'/' -f1
a

$ echo 'a/b/c/d/e/f/g/h/i' | cut -d'/' -f5
e
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文