从 UNIX 中的文本文件中提取特定文本
我在 UNIX shell 脚本编写方面遇到一些问题,特别是文件读取方面。我希望最终产品是让脚本将文本文件作为命令行参数,然后提取某些部分以在各种操作中使用。文本文件将如下所示:
ABC12345:John Smith:78
DEF12345:Jane Doe:80
GHI12345:Bob Johnson:91
并且它将像其他几行一样继续。现在,我到目前为止所做的提取最后一个冒号后面的数字的代码片段如下:
case $1 in
m)cat $2 | while read -r file; do
#gets the numbers from 0 to 100
current=grep [0-100]
case 语句只是因为最终用户将能够以不同的方式运行程序。然而,代码段的主要思想是获取文本文件中行末尾的 2 位数字并将其存储在当前变量中。
其余的操作确实围绕这个想法,但是,我不完全确定如何提取中间的名称。
无论如何,任何帮助都会很棒!请记住,我对此很陌生。
I'm having some problems with UNIX shell scripting, specifically file reading. What I would like the end product to be is for the script to take a text file as a command line argument and then extract certain parts to use in various operations. The text file would look like this:
ABC12345:John Smith:78
DEF12345:Jane Doe:80
GHI12345:Bob Johnson:91
and it would continue like that with several other lines. Now what I have done so far to extract the number after the last colon is here in this code snippet:
case $1 in
m)cat $2 | while read -r file; do
#gets the numbers from 0 to 100
current=grep [0-100]
The case statement is just because in the end the user will be able to run the program different ways. The main idea in the code segment however is to take the 2-digit number at the end of the line in the text file and store it in the current variable.
The rest of the operations really revolve around this idea, however, I'm not entirely sure how to extract the name in the middle.
Anyway, any help would be great! Just please keep in mind I am very new to this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如 Frankc 所建议的,awk 或 cut 效果很好。您还可以摆弄
IFS
和(假设是 Bash)数组:As frankc suggests, awk or cut would work well. You could also fiddle with
IFS
and (assuming Bash) arrays:试试这个:
这将回显每行的第三个字段。修改以满足您的需要。
Try this:
That will echo the third field of each line. Modify to suit your needs.
有很多方法可以提取您的案例中的姓名和分数。参见示例:
cut 也可以做到。
there are many ways to extract name and score in your case. see example:
cut can do it as well.
AWk -F: '{print $NF}' 文件名
AWk -F: '{print $NF}' file_name