问题
I'm trying to create AWK script that will filter the input file according to some pattern, and use the strftime() function for some calculations.
($2 ~ /^[HB]/ && $2 ~ /n$/){
print strftime("%Y")
}
The interpreter in use is mawk. When triggering this script using this command:
awk -f script3 inputFile
I'm getting the error: "function strftime never defined"
回答1:
Installing GAWK will get you the function strftime back that you are missing natively in awk.
With Ubuntu 11.10 or simiar distribution you would issue following command to get the GAWK
sudo apt-get install gawk
You can also use it in gawk however you don't have to and can simply go ahead with your original awk script.
回答2:
Well, clearly, mawk does not have a strftime function.
I don't have mawk here, so untested:
awk -f script -v the_year=$(date "+%Y") inputFile
and script
has (combining the two regular expressions:
$2 ~ /^[HB].*n$/ { print the_year }
If the year should come from $0 somehow, then you should be able to parse it out of the string. Give us more details about your input.
EDIT
the input is made of several rows that look like this: "12768 Ashwari F 20 11 1985". Basically I have to filter all those with a name that begins with B or H and ends with n. In addition I have to calculate the age of each filtered student and find out the average age of the entire group.
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
来源:https://stackoverflow.com/questions/3684212/using-strftime-function-in-mawk