我有一个基于文本的数据库文件,用于存储学生条目,如下所示:
SID:LNAME:FNAME:hw01:quiz01
004:dravid:rahul:78:100
002:ganguly:sourav:54:13
005:kohli:virat:48:43
001:kumble:anil::54
003:tendulkar:sachin:87:78
用户输入他想要更新的标题和学生的sid / lname / fname。因此,例如,如果用户输入
sid = 001,hw01,得分= 19,我想要输出如下:
SID:LNAME:FNAME:hw01:quiz01
004:dravid:rahul:78:100
002:ganguly:sourav:54:13
005:kohli:virat:48:43
001:kumble:anil:19:54
003:tendulkar:sachin:87:78
我意识到awk是最好的方法。知道怎么做吗?
感谢。
答案 0 :(得分:5)
您可以使用此awk命令:
awk -v sid='001' -v hw01='19' 'BEGIN {FS=OFS=":"} $1 == sid { $4 = hw01 } 1' file
SID:LNAME:FNAME:hw01:quiz01
004:dravid:rahul:78:100
002:ganguly:sourav:54:13
005:kohli:virat:48:43
001:kumble:anil:19:54
003:tendulkar:sachin:87:78
更新:根据以下评论,此awk命令接受搜索&更新列名和值。
awk -v skey='SID' -v sval='001' -v ukey='hw01' -v uval='19' 'BEGIN { FS=OFS=":" }
NR==1{for (i=1; i<=NF; i++) col[$i]=i} $col[skey]==sval{ $col[ukey]=uval } 1' file
SID:LNAME:FNAME:hw01:quiz01
004:dravid:rahul:78:100
002:ganguly:sourav:54:13
005:kohli:virat:48:43
001:kumble:anil:19:54
003:tendulkar:sachin:87:78
答案 1 :(得分:3)
$ cat tst.awk
BEGIN { FS=OFS=":" }
{
if (NR==1) {
for (i=1; i<=NF; i++) {
name2num[tolower($i)] = i
}
# upd="sid=001,hw01=19"
split(tolower(upd),tmp,/[=,]/)
keyNum = name2num[tmp[1]]
keyVal = tmp[2]
tgtNum = name2num[tmp[3]]
tgtVal = tmp[4]
}
else {
if ($keyNum == keyVal) {
$tgtNum = tgtVal
}
}
print
}
$ awk -v upd="sid=001,hw01=19" -f tst.awk file
SID:LNAME:FNAME:hw01:quiz01
004:dravid:rahul:78:100
002:ganguly:sourav:54:13
005:kohli:virat:48:43
001:kumble:anil:19:54
003:tendulkar:sachin:87:78
$ awk -v upd="lname=dravid,quiz01=54" -f tst.awk file
SID:LNAME:FNAME:hw01:quiz01
004:dravid:rahul:78:54
002:ganguly:sourav:54:13
005:kohli:virat:48:43
001:kumble:anil::54
003:tendulkar:sachin:87:78