使用system()在awk中进行sed无法正常工作 [英] sed inside awk with system() is not working
问题描述
我有一个文件,用于存储学生所修课程的内容:
I have a file storing the course content taken by a student:
示例outputA
:
------------------------------------------------------------------------------------------------------------------------
Year Semester Code Credits Tag letterGrade
------------------------------------------------------------------------------------------------------------------------
2019 Autumn CS 753 6 Department elective AB
2019 Autumn CS 490 6 Honors core CC
2019 Autumn CS 492 6 Honors core FR
2019 Autumn CS 747 6 Department elective FF
2019 Autumn ES 200 3 Basic Sciences BC
2019 Autumn ET 601 6 Institute Elective BB
我想使用bash脚本将它们回显到终端,并且每行都根据课程标记进行着色. 有关如何着色的信息在另一个文件中给出:
I want to echo them to a terminal using a bash script with each line colored according to the course tag. The information on how to color is given in another file:
源CSV以处理./resources/creditsRequirements.csv
:
tag,credits,color_FONT,color_BACKGROUND,
Basic Sciences,62,CYAN,BLACK,
Engineering Science,29,BLACK,GREEN,
HSS Elective,12,GREEN,BLACK,
Institute Elective,12,BLACK,WHITE,
Core course,117,BLACK,CYAN,
Department elective,36,YELLOW,BLACK,
Honors core,24,WHITE,BLACK,
Minor,30,MAGENTA,WHITE,
Additional Learning,0,RED,WHITE,
除了sed
或awk
,我不能使用任何其他命令.
I can't use any command other than sed
or awk
.
我想做这样的事情(outputA
和./resources/creditRequirements.csv
是命令行参数):
I want to do something like this (outputA
and ./resources/creditRequirements.csv
are command line arguments):
awk -F"," 'NR!=1{system("sed -e 's/^.\{1,\}($1).\{1,\}$/(code for color)&(code for reset)/g' "$1)}' $2
但是这正在发生(我使用了一个较短的sed命令只是为了对其进行测试):
But this is happening (I used a shorter sed command just to test it):
./viewWithColor.sh outputA ./resources/creditsRequirements.csv
awk: cmd. line:1: NR!=1{system("sed -e /[0-9]/
awk: cmd. line:1: ^ unterminated string
awk: cmd. line:1: NR!=1{system("sed -e /[0-9]/
awk: cmd. line:1: ^ syntax error
推荐答案
您只能使用awk
来做到这一点:
You can do this with awk
only:
colored.awk
#!/usr/bin/awk -f
function color_code(name) {
switch(name) {
case "BLACK":
return 30
case "RED":
return 31
case "GREEN":
return 32
case "YELLOW":
return 33
case "BLUE":
return 34
case "PURPLE":
return 35
case "CYAN":
return 36
case "WHITE":
return 37
default:
return 37
}
}
function colored(str, fg_name, bg_name) {
fg_code = color_code(fg_name)
# The background color codes are the foreground color codes + 10
bg_code = color_code(bg_name) + 10
return "\033["fg_code";"bg_code"m"str"\033[0m"
}
# Read color assignments
NR==FNR {
if (NR < 2) {
next
}
split($0,a,",")
f[a[1]]=a[3]
b[a[1]]=a[4]
next
}
{
for (i in f) {
repl = colored(i, f[i], b[i])
$0 = gensub(i, repl, 1)
}
print
}
使文件可执行,并像这样运行它:
Make the file excutable and run it like this:
chmod +x colored.awk
./colored.awk resources/creditsRequirements.csv outputA
这篇关于使用system()在awk中进行sed无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!