在mawk中使用strftime函数

Ari*_*l.T 8 awk strftime

我正在尝试创建将根据某种模式过滤输入文件的AWK脚本,并使用strftime()函数进行一些计算.

($2 ~ /^[HB]/ && $2 ~ /n$/){
        print strftime("%Y")
}
Run Code Online (Sandbox Code Playgroud)

使用的翻译是mawk.使用此命令触发此脚本时:

awk -f script3 inputFile
Run Code Online (Sandbox Code Playgroud)

我收到错误:"函数strftime从未定义"

小智 13

安装GAWK会让你获得strftime功能,因为你在awk中本身就缺少了这个功能.

使用Ubuntu 11.10或simiar发行版,您可以发出以下命令来获取GAWK

sudo apt-get install gawk

您也可以使用gawk,但是您不必使用它,并且可以简单地继续使用您的原始awk脚本.


gle*_*man 3

嗯,很明显,mawk没有 strftime 函数。

我这里没有 mawk,所以未经测试:

awk -f script -v the_year=$(date "+%Y") inputFile
Run Code Online (Sandbox Code Playgroud)

并且script具有(组合两个正则表达式:

$2 ~ /^[HB].*n$/ { print the_year }
Run Code Online (Sandbox Code Playgroud)

如果年份应该以某种方式来自 $0,那么您应该能够从字符串中解析它。请向我们提供有关您的意见的更多详细信息。

编辑

输入由几行组成,如下所示:“12768 Ashwari F 20 11 1985”。基本上我必须过滤所有名称以 B 或 H 开头并以 n 结尾的名称。此外,我还必须计算每个过滤学生的年龄,并找出整个组的平均年龄。

awk -v this_year=$(date +%Y) -v today=$(date +%Y%m%d) '
    $2 ~ /^[BH].*n$/ {
        age = this_year - $6
        if (today < $6 $5 $4) { age-- } # I assume those fields are the birthday 
        total_age += age
        count ++
        print $2 " is " age " years old"
    }
    END {
        print "average age = " total_age/count
    }
' inputFile
Run Code Online (Sandbox Code Playgroud)