Shell 脚本编写 - 如何正确解析输出,学习示例。
因此,我想使用 shell 脚本自动执行手动任务,但我对如何解析一些命令的输出有点迷失。我可以用其他语言毫无问题地做到这一点,所以我将只解释我要在伪代码中做什么,并提供我试图解析的 cmd 输出的示例。
输出示例:
2012/02/13 由 user1234@filename“提交说明”更改为 2167467
我需要解析的是'2167467'。所以我想做的是按空格分割并取出元素 1 在另一个命令中使用。我的下一个命令的输出如下所示:
user1234@filename 于 2012/02/13 18:10:15 更改 2167463
提交说明
受影响的文件...
... //文件路径/dir1/dir2/dir3/filename#2298编辑
我需要解析 '//filepath/dir1 /dir2/dir3/filename#2298' 并在另一个命令中使用它。同样,我要做的就是从输出中删除空白行,抓住第四行,然后按空格分割。从那里我将从拆分中获取第一个元素并在下一个命令中使用它。
我怎样才能在 shell 脚本中做到这一点?示例或一些教程的要点会很棒。
So I want to automate a manual task using shell scripting, but I'm a little lost as to how to parse the output of a few commands. I would be able to this in other languages without a problem, so I'll just explain what I'm going for in psuedo code and provide an example of the cmd output I'm trying to parse.
Example of output:
Chg 2167467 on 2012/02/13 by user1234@filename 'description of submission'
What I need to parse out is '2167467'. So what I want to do is split on spaces and take element 1 to use in another command. The output of my next command looks like this:
Change 2167463 by user1234@filename on 2012/02/13 18:10:15
description of submission
Affected files ...
... //filepath/dir1/dir2/dir3/filename#2298 edit
I need to parse out '//filepath/dir1/dir2/dir3/filename#2298' and use that in another command. Again, what I would do is remove the blank lines from the output, grab the 4th line, and split on space. From there I would grab the 1st element from the split and use it in my next command.
How can I do this in shell scripting? Examples or a point to some tutorials would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不清楚是否要使用第一个命令的结果来处理第二个命令。如果这是真的,那么
您的示例数据中有 2 个不同的 Chg 值(2167467、2167463),因此如果您只想以两种不同的方式处理此输出,那么它就更简单了,
我希望这会有所帮助。
Its not clear if you want to use the result from the first command for processing the 2nd command. If that is true, then
Your example data has 2 different Chg values in it, (2167467, 2167463), so if you just want to process this output in 2 different ways, its even simpler
I hope this helps.
我不是 100% 清楚你的问题,但我会使用 awk。
http://www.cyberciti.biz/faq/bash-scripting-using- awk/
I'm not 100% clear on your question, but I would use awk.
http://www.cyberciti.biz/faq/bash-scripting-using-awk/
您的第一个变量看起来像这样
要获取您想要的数字,请执行以下操作:
将第二个命令的输出保存到类似这样的文件中
要从文件中获取您想要的内容,您可以运行以下命令:
最后一个代码块获取文件的最后一个非白色行并在第二组空格上进行分隔
Your first variable would look something like this
To get the number you want do this:
Let the output of your second command be saved to a file something like this
To get what you want from the file you can run this:
The last block of code gets the last nonwhite line of the file and delimits on the second set of white spaces