我正在编写一个 ksh 脚本,其场景如下:
我有一个学生报告的文本文件,其中包含学生的详细信息,例如:
Student_1
Name: ABC
Class:X
Head Teacher:SITA
Status: Pass
Student_1
Name: ABCE
Class:X
Head Teacher:SITA
Status: Pass
Student_2
Name:ABCD
Class:XI
Head Teacher:RYAN
Status: Fail
Student_50:
Name:MIKE
Class:X
Head Teacher:RYAN
Status:Fail
我需要做的是
Student_N
通过计算以;开头的行来查找学生人数计算有多少学生通过了这条线,有多少学生未能通过该
Status:
线。- 查找姓名以 A 开头的学生的姓名。
我尝试了很多事情,包括:
sed -n '/Student_i<< Status/,/Status/p' students_details.txt >> report_card.txt
sed '/^Student_i<< Status/,/)/Status/$/!d/Status/s/^Student_i<< Status (///Status/s/);$//' students_details.txt >> report_card.txt
sed '/^Student_i<< Status/,/)Status$/!d;s/^Student_i<< Status (//;s/);$//' students_details.txt >> report_card.txt
sed '/^pass/,/);$/!d;s/^pass (//;s/);$//' students_details.txt>> report_card.txt
我想要的输出文件是:
对于第 1 点:
Student_1 : 2 Student_2 : 1 Student_50: 1
对于第 2 点:
Pass: 2 Fail: 2
对于第 3 点:
Count of Students whose name starts with "A" : 3
答案1
就我个人而言,我会用 Perl 完成整个事情:
$ perl -00ne '/^(Student_\d+)/ && $count{$1}++;
/Name:\sA/ && $As++;
/Status:\s*Pass/ ? $pass++ : $fail++;
END{
print "$_ : $count{$_}\n" for keys(%count);
print "Pass: $pass\nFail:$fail\n";
print "Student names starting with A: $As\n"
}' file
Student_2 : 1
Student_1 : 1
Student_50 : 1
Pass: 2
Fail:2
Student names starting with A: 2
如果您坚持每个操作使用单独的命令,您可以使用:
$ awk '/^Student_/{a[$0]++} END{for(s in a){print s,a[s]}}' file
Student_1 1
Student_2 1
Student_50: 1
$ perl -ne '$pass++ if /:\s*Pass/; $fail++ if /:\s*Fail/;
END{print "Pass: $pass\nFail: $fail\n"}' file
Pass: 2
Fail: 2
$ echo "Student names starting with A: $(grep -c "^Name:\s*A" file )"
Student names starting with A: 2