2010-09-10 25 views
7

我想創建AWK腳本,它將根據某種模式篩選輸入文件,並使用strftime()函數進行一些計算。在makk中使用strftime函數

($2 ~ /^[HB]/ && $2 ~ /n$/){ 
     print strftime("%Y") 
} 

使用中的解釋器是mawk。 使用此命令時觸發此腳本:

awk -f script3 inputFile 

,我發現了錯誤:「功能的strftime從來沒有定義」

回答

3

好吧,很顯然,mawk沒有一個strftime函數。

我沒有mawk這裏,所以未經測試:

awk -f script -v the_year=$(date "+%Y") inputFile 

script已經(結合了兩個正則表達式:

$2 ~ /^[HB].*n$/ { print the_year } 

如果一年要來從$ 0弄好了,然後你應該能夠從字符串中解析出來。給我們提供關於你輸入的更多細節。

編輯

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 
+0

嗨格倫,輸入是由幾行看起來像這樣:「12768 Ashwari F 20 11 1985」。基本上我必須過濾所有以'B'或'H'開頭並以'n'結尾的名字。另外,我必須計算每位篩選出來的學生的年齡,並找出整個組的平均年齡。乾杯,阿里爾。 – 2010-09-11 19:53:30

+0

這是一個好主意,在某些情況下可以使用。但有時您需要重複時間戳調用,例如,用於日誌消息,並且在這種情況下它不起作用。 – erikbwork 2016-01-08 18:23:24

12

安裝GAWK將讓你的函數strftime的背部,你是在本地AWK失蹤。

與Ubuntu 11.10或simiar分佈您會發出以下命令來獲得GAWK

sudo apt-get install gawk

你也可以用它在GAWK但是你沒有,可以簡單地用你原來的繼續awk腳本。

+0

我爲我做了這份工作。謝謝 – codersofthedark 2014-09-15 06:46:09

+1

@Ariel:如果這對您也有用,請將其標記爲正確答案 – codersofthedark 2014-09-15 06:46:43