【bash学习009】一个awk例子

代码来自ABS(高级bash脚本编程指南),其中有一处错误,不隐蔽,但查找这个错误有利于理解awk。

View Code
 1 #! /bin/sh

 2 # letter-count2.sh: Counting letter occurrences in a text file.

 3 #

 4 # Script by nyal [[email protected]].

 5 # Used in ABS Guide with permission.

 6 # Recommented and reformatted by ABS Guide author.

 7 # Version 1.1: Modified to work with gawk 3.1.3.

 8 #              (Will still work with earlier versions.)

 9 

10 

11 INIT_TAB_AWK=""

12 # Parameter to initialize awk script.

13 count_case=0

14 FILE_PARSE=$1

15 

16 E_PARAMERR=85

17 

18 usage()

19 {

20     echo "Usage: letter-count.sh file letters" 2>&1

21     # For example:   ./letter-count2.sh filename.txt a b c

22     exit $E_PARAMERR  # Too few arguments passed to script.

23 }

24 

25 if [ ! -f "$1" ] ; then

26     echo "$1: No such file." 2>&1

27     usage                 # Print usage message and exit.

28 fi 

29 

30 if [ -z "$2" ] ; then

31     echo "$2: No letters specified." 2>&1

32     usage

33 fi 

34 

35 shift                      # Letters specified.

36 for letter in `echo $@`    # For each one . . .

37   do

38   INIT_TAB_AWK="$INIT_TAB_AWK tab_search[${count_case}] = \

39   \"$letter\"; final_tab[${count_case}] = 0; " 

40   # Pass as parameter to awk script below.

41   count_case=`expr $count_case + 1`

42 done

43 

44 # DEBUG:

45 # echo $INIT_TAB_AWK;

46 

47 cat $FILE_PARSE |

48 # Pipe the target file to the following awk script.

49 

50 # ---------------------------------------------------------------------

51 # Earlier version of script:

52 # awk -v tab_search=0 -v final_tab=0 -v tab=0 -v \

53 # nb_letter=0 -v chara=0 -v chara2=0 \

54 

55 awk \

56 "BEGIN { $INIT_TAB_AWK } \

57 { split(\$0, tab, \"\"); \

58 for (chara in tab) \

59 { for (chara2 in tab_search) \

60 { if (tab_search[chara2] == tab[chara]) { final_tab[chara2]++ } } } } \

61 END { for (chara in final_tab) \

62 { print tab_search[chara] \" => \" final_tab[chara] } }"

63 # ---------------------------------------------------------------------

64 #  Nothing all that complicated, just . . .

65 #+ for-loops, if-tests, and a couple of specialized functions.

66 

67 exit $?

68 

69 # Compare this script to letter-count.sh.

揭晓答案(答案用了白色字体,全选就能看见),在第57行,应将\"\"改成\" \",在中间加入一个空格。

你可能感兴趣的:(bash)