使用Shell脚本从行或字符串中提取文本

发布于 2025-02-01 18:43:12 字数 590 浏览 4 评论 0原文

我的文本文件中有以下数据。我知道如何在Shell脚本中循环循环。只需要帮助了解我将如何从文件中的以下字符串中排出 abc或tes或hyj或vvb

!abc { xyz: "ABC", queue: "TEST" },
!abc { xyz: "TES", queue: "TEST" },
!abc { xyz: "HYJ", queue: "TEST" },
!abc { xyz: "VVB", queue: "TEST" },

上述数据的格式将保持不变。.

我已经尝试了以下建议

#!/bin/bash

line1="!abc { xyz: "ABC", queue: "TEST" },"
echo $line1
test_data=$(echo $line1 | grep -Eoh '!abc { xyz: ".*?"' | cut -d\" -f3)
echo $test_data

的上述代码的建议。

预期输出应为test_data = ABC 如果我们这样做“ echo $ test_data”,它应该给我ABC

I have below data in my text file. I know how to loop through the line in shell script. Just need help in understanding how will I take out only ABC or TES or HYJ or VVB line by line from the below strings in a file.

!abc { xyz: "ABC", queue: "TEST" },
!abc { xyz: "TES", queue: "TEST" },
!abc { xyz: "HYJ", queue: "TEST" },
!abc { xyz: "VVB", queue: "TEST" },

The format of the above data will remain same..

I have tried this below suggestion

#!/bin/bash

line1="!abc { xyz: "ABC", queue: "TEST" },"
echo $line1
test_data=$(echo $line1 | grep -Eoh '!abc { xyz: ".*?"' | cut -d\" -f3)
echo $test_data

For the above code nothing is getting outputted.

Expected Output should be test_data = ABC
If we do "echo $test_data" it should give me ABC

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

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

发布评论

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

评论(2

你げ笑在眉眼 2025-02-08 18:43:14

美好的一天,

剪切命令:$ cut -d'“''-f2 file.txt

,它用定界符''''''''''''''''。

Good day,

how about the cut command: $cut -d'"' -f2 file.txt

which cut out the second field with delimiter '"' .

奈何桥上唱咆哮 2025-02-08 18:43:14

有多种方法,这是一个非常简单的方法:

  1. cat file.txt打印出文件的内容

  2. awk的内容用于将行分为两个部分,一个是“:”之前的一个。

  3. 另一个尴尬命令被用来将结果输出再次分为两个部分,一个在“”之前,一个之后

  4. 最后一个使用SED命令来删除双引号”

    cat file.txt | awk -f“:”'{print $ 2}'| awk -f“,”,'{print $ 1}'| sed -e's/s/“ //'-e's/” $ //'

There are multiple ways of doing this, here is one, that is really simple:

  1. cat file.txt prints out the contents of the file

  2. AWK is used to divide the line into two parts, one prior to ":" and another one after it.

  3. Another AWK command is being used to divide the resulting output into two parts again, one before "," and one after it

  4. Lastly SED command is used to remove the double quotes ""

    cat file.txt | awk -F ":" '{print $2}' | awk -F "," '{print $1}' | sed -e 's/"//' -e 's/"$//'

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