在 macOS 终端中使用 Shell 查找文件中的单词。

huangapple go评论61阅读模式
英文:

Finding a word in a file using Shell in Terminal on macOS

问题

我有一个文本文件,其中有一行,如下所示:

Submitting job with ID: 50fd2805-6fcc-4bc6-91a2-638528180ab6

(这是完整的一行,之前和之后还有其他行。)

我需要找到并提取ID到一个变量中。我想出了一个正则表达式模式:

[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}

这个模式应该有效,但似乎在Shell中无论我尝试什么都不起作用:grep、sed等。

我的一次尝试是这样的:

JOB_ID=$(grep '[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}' file)

明确一下,我希望JOB_ID包含字符串"50fd2805-6fcc-4bc6-91a2-638528180ab6"(不带引号)。

对于这个看似初学者的问题,我感到抱歉,但我在互联网上找不到任何答案:我已经阅读了数十个类似的问题在SO和SE上,还搜索了几个教程,但仍然无法找到答案。

感谢任何指导!

英文:

I have a text file with a line among others:

Submitting job with ID: 50fd2805-6fcc-4bc6-91a2-638528180ab6

(It's a full line, and it has other lines before and after.)

I need to find and extract to a variable the ID. I came up with a RexEx pattern:

[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}

The patterns should work, but it doesn't seem to work in Shell with anything I tried: grep, sed – whatever.

One of my attempts was this:

JOB_ID=$(grep '[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}' file)

To be clear, as a result I need JOB_ID to contain string "50fd2805-6fcc-4bc6-91a2-638528180ab6" (without quotes.)

I'm sorry for such a seemingly noob question, but I couldn't find anything on the internet: I've read dozens of similar questions on SO and SE, and googled several tutorials, and still couldn't figure out the answer.

Any guidance is appreciated!

答案1

得分: 1

你可以使用 awk 来打印以 Submitting 开头的行中的最后一个字段,如下所示:

JOB_ID=$(awk '/^Submitting/ {print $NF}' file)
英文:

You could use awk to print the last field on a line starting Submitting like this:

JOB_ID=$(awk '/^Submitting/ {print $NF}' file)

huangapple
  • 本文由 发表于 2023年2月8日 20:02:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定