Linux系统awkAwk

awk基础05-自定义函数和脚本

2018-10-24  本文已影响6人  Surpassme

    在之前文章中,我们都是在命令行中写一些简短的awk命令,而awk做为一门解释型语言,一样是支持脚本运行的。

基本语法

#!/bin/awk -f
# 注释
awk 脚本体

脚本示例

1、第一个示例

[root@localhost awk]# vim test.awk
[root@localhost awk]# cat test.awk
#!/bin/awk -f
BEGIN {print "this is test awk script"}
[root@localhost awk]# chmod +x test.awk
[root@localhost awk]# ./test.awk
this is test awk script

2、第二个示例

[root@localhost awk]# vim passwd.awk
[root@localhost awk]# cat passwd.awk
#!/bin/awk -f
BEGIN {FS=":"}
/root/ {print "Username is:"$1,"UID is:"$3,"GID is:"$4,"Shell is:"$NF}
[root@localhost awk]# chmod +x passwd.awk
[root@localhost awk]# ./passwd.awk  /etc/passwd
Username is:root UID is:0 GID is:0 Shell is:/bin/bash
Username is:operator UID is:11 GID is:0 Shell is:/sbin/nologin

自定义函数

    前面已经学习了awk内置的函数,相信大家已经有所理解和掌握了,本文我们将还学习一下awk自定义函数。

基本语法

function FunctionName(parameter list)
{
statements
return 表达式或结果
}

自定义函数示例

[root@localhost awk]# vim functions.awk
[root@localhost awk]# cat functions.awk

#!/bin/awk -f

# define function
function Add(firstNum,secondNum)
{
  sum=0
  for(i=firstNum;i<=secondNum;i++)
   {
     sum=sum+i;
   }
  return sum
}

function main(num1,num2)
{
 result=Add(num1,num2)
 print "Sum is :",result
}

# execute function
BEGIN { main(1,100) }

[root@localhost awk]# chmod +x functions.awk
[root@localhost awk]# ./functions.awk
Sum is : 5050

    到此awk的基础知识已经介绍完毕,当然如果想更深入学习awk知识,则还多查阅相关资料。

上一篇下一篇

猜你喜欢

热点阅读