如何从字符串中提取信息
我正在尝试从使用 bash 运行的负载中获取动态。我已经得到了我想要的字符串,现在我想从中提取某些可能变化的信息。返回的字符串如下:
Records: 2910 Deleted: 0 Skipped: 0 Warnings: 0
每个数字的长度可以并且将会变化,但整体结构将保持不变。我想要做的是能够获取这些数字并将它们加载到一些 bash 变量中,即:
RECORDS=??
DELETED=??
SKIPPED=??
WARNING=??
在正则表达式中我会这样做:
Records: (\d*?) Deleted: (\d*?) Skipped (\d*?) Warnings (\d*?)
并在我的变量中使用 4 个组。
I am trying to pull dynamics from a load that I run using bash. I have gotten to a point where I get the string I want, now from this I want to pull certain information that can vary. The string that gets returned is as follows:
Records: 2910 Deleted: 0 Skipped: 0 Warnings: 0
Each of the number can and will vary in length, but the overall structure will remain the same. What I want to do is be able to get these numbers and load them into some bash variables ie:
RECORDS=??
DELETED=??
SKIPPED=??
WARNING=??
In regex I would do it like this:
Records: (\d*?) Deleted: (\d*?) Skipped (\d*?) Warnings (\d*?)
and use the 4 groups in my variables.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在 Bash 版本 >= 3.2 中使用正则表达式匹配:
You can use regex matching in Bash versions >= 3.2:
内置的
read
命令可以解决这个问题:更新:您还可以使用
set
:Built-in
read
command will do the trick:Update: You can also use
set
:您可以使用以下 shell 函数来创建多个名称/值对。它假设内容的格式如您所说,但很容易更改:
像这样执行:
Here's a shell function you can use that just creates a number of name/value pairs. It assumes things are formatted as you said, but is easy to change:
Execute it like:
您可以根据行的结构尝试使用“sed”或“cut”,如下所示:
You can try something with 'sed' or 'cut' depending on the structure of the line like this:
输出
output