我正在尝试为与某些文本字段匹配的作业创建一个bash脚本,并以特定格式打印它们。我正在尝试获取课程编号,标题和学分小时数(从十进制转换为整数)并将其输出到名为course_list
的文件。
示例输入:
CSC 1010 - COMPUTERS & APPLICATIONS
Computers and Applications. Prerequisite: high school Algebra II. History of computers, hardware components, operating systems, application software, data communication.
3.000 Credit hours
这就是我所拥有的:
#!/bin/bash
awk '/CSC/ {print $1$2","$4,$5,$6,$7,$8,$9} /[0-9].(000)/ {print substr(","$1,1,2)}' courses.txt | cat >> course_list
这是我得到的输出:
CSC1010,COMPUTERS & APPLICATIONS
,3
这是我想要的输出:
CSC1010,COMPUTERS & APPLICATIONS,3
我认为我非常接近但我无法弄清楚如何在没有\n
的情况下打印两个单独的比赛。
答案 0 :(得分:1)
$ cat file
CSC 1010 - COMPUTERS & APPLICATIONS
Computers and Applications. Prerequisite: high school Algebra II. History of computers, hardware components, operating systems, application software, data communication.
3.000 Credit hours
$ awk '/CSC/{split($0,a,/ - /); gsub(/ /,"",a[1])} /[0-9].000/{printf "%s,%s,%d\n",a[1],a[2],$1}' file
CSC1010,COMPUTERS & APPLICATIONS,3
答案 1 :(得分:0)
使用sed:
sed -n 's/CSC[^-]*-[ ]*\([^\.]*\).*\([0-9][0-9]*\)\.000[ ]*Credit.*/\1,\2/p' input
答案 2 :(得分:0)
awk '{print $1$2","$4,$5,$6","$(NF-2)}' RS= course_list
说明:
NF
是一个存储字段数的内部变量。 $NF
保存最后一个字段的值。由于OP希望捕获NF-2
位置的课程时间,我们打印出来。
答案 3 :(得分:0)
@Powdercake,是的,这很接近。只需将{print substr(","$1,1,2)}
更改为{print $1+0}
即可将$1
强制转换为(默认)数字格式(并省略管道和cat之类的内容,如@John Zwinck所述)