如何使用SED使用字符串作为搜索参数提取字符串

发布于 2025-01-20 23:54:22 字数 696 浏览 6 评论 0原文

我试图返回一个通过输出不断变化的字符串。 我认为 grep 和 sed 可能是处理这个问题的最佳方法。 基本上,输出呈现一个大的文本字段,其中包含一些内容,目标

https://rancher.website.com/version1/proj/abcd123?somethingsomethingsomethingetc

是返回第一个实例,

https://rancher.website.com/version1/proj/

因为有多个实例,然后返回 abcd123 的内容,直到 ? 符号之前。

我一直在尝试调整 sed 命令,但我的语法不断出错,而且我很难理解到目前为止给出的解释。我认为我的问题之一可能是因为 sed “搜索”缺乏更好的术语,是针对字符串而不是单个字符运行的。另外,正斜杠也是一个问题,因为我认为它们在 sed 命令中被解释为运算符?

我尝试使用的命令或多或少是:

grep 'https://rancher.website.com/version1/projects/' grep.txt | sed 's/^.*'https:\/\/rancher.website.com\/version1\/projects\/'//g'

grep.txt 是初始命令的输出文本的容器

I am trying to return a string that is constantly changing via the output.
I decided grep and sed might be the best way to handle this.
Basically the output renders a large field of text that contains something to the effect of

https://rancher.website.com/version1/proj/abcd123?somethingsomethingsomethingetc

the goal is to return the FIRST instance of

https://rancher.website.com/version1/proj/

as there are multiple, and then return the contents of abcd123 up to the ? symbol before it.

I keep trying to tweak the sed command but keep running into errors with my syntax and I am having trouble wrapping my mind around the explanations given so far. I think one of my problems might be around the fact that the sed "search" for lack of a better term, is being run against a string rather than a single character. Also the forward slashes are a problem as I think those are being interpreted as operators in the sed command?

Command I am trying to use is more or less:

grep 'https://rancher.website.com/version1/projects/' grep.txt | sed 's/^.*'https:\/\/rancher.website.com\/version1\/projects\/'//g'

With grep.txt being the container for the output text of the initial command

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

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

发布评论

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

评论(1

一身软味 2025-01-27 23:54:22

将最后一个 / 之前的所有内容以及 ? 中的所有内容替换为空字符串。

grep -m 1 'https://rancher.website.com/version1/projects/' grep.txt | 
    sed -e 's#.*/##' -e 's#\?.*##'

当模式包含 / 时,请使用不同的字符作为 s 分隔符以避免必须对其进行转义;我在上面使用了#

Replace everything up to the last / and everything from ? with empty strings.

grep -m 1 'https://rancher.website.com/version1/projects/' grep.txt | 
    sed -e 's#.*/##' -e 's#\?.*##'

When the pattern includes /, use a different character as the s delimiter to avoid having to escape it; I've used # above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文