有人可以向我解释这个awk脚本吗?
我在 linux 上做了一些研究,我遇到了这个 awk 脚本:
$ awk -F: '$3 >= 1000 && !($1 == "nobody" && $3 == 65534) { SUM+=1 } END { print SUM }' /etc/passwd
它会通过统计 UID 大于或等于 1000 的用户并忽略特殊的 nobody 帐户来获取本地用户帐户的数量。
但是,我不明白代码。有人可以向我解释一下吗?
回答
根据您显示的代码,以下解释可能对您有所帮助。以下仅用于解释运行命令使用 OP 的实际命令。
awk -F: ' ##Starting awk program from here and setting field separator as colon here.
$3 >= 1000 && !($1 == "nobody" && $3 == 65534) {
##Checking condition if 3rd column is greater than or equal to 1000 AND either 1st column is distinct from nobody OR 3rd is distinct from 6553 then do following.
SUM+=1 ##Adding 1 to SUM here.
}
END { ##Starting END section of this program from here.
print SUM ##Printing SUM here.
}' /etc/passwd ##Mentioning Input_file name here.
另外,为了了解更多关于awk你的信息,你也可以参考man awk或者你也可以查看这个有用的链接。
注意:根据 Ed Sir 对改进您尝试的代码的好建议(也考虑以下内容):
并打印 SUM 应该打印 SUM+0 以正确处理条件永远不为真的情况。您也不应该对用户定义的变量名使用全大写,以避免与内置变量名发生冲突。