Debian Codegraph @

awklib/eg/prog/wc.awk

raw
1 # wc.awk --- count lines, words, characters, bytes
2 #
3 # Arnold Robbins, [email protected], Public Domain
4 # May 1993
5 # Revised September 2020
6
7 # Options:
8 # -l only count lines
9 # -w only count words
10 # -c only count bytes
11 # -m only count characters
12 #
13 # Default is to count lines, words, bytes
14 #
15 # Requires getopt() and file transition library functions
16 # Requires mbs extension from gawkextlib
17
18 @load "mbs"
19
20 BEGIN {
21 # let getopt() print a message about
22 # invalid options. we ignore them
23 while ((c = getopt(ARGC, ARGV, "lwcm")) != -1) {
24 if (c == "l")
25 do_lines = 1
26 else if (c == "w")
27 do_words = 1
28 else if (c == "c")
29 do_bytes = 1
30 else if (c == "m")
31 do_chars = 1
32 }
33 for (i = 1; i < Optind; i++)
34 ARGV[i] = ""
35
36 # if no options, do lines, words, bytes
37 if (! do_lines && ! do_words && ! do_chars && ! do_bytes)
38 do_lines = do_words = do_bytes = 1
39
40 print_total = (ARGC - i > 1)
41 }
42 function beginfile(file)
43 {
44 lines = words = chars = bytes = 0
45 fname = FILENAME
46 }
47 function endfile(file)
48 {
49 tlines += lines
50 twords += words
51 tchars += chars
52 tbytes += bytes
53 if (do_lines)
54 printf "\t%d", lines
55 if (do_words)
56 printf "\t%d", words
57 if (do_chars)
58 printf "\t%d", chars
59 if (do_bytes)
60 printf "\t%d", bytes
61 printf "\t%s\n", fname
62 }
63 # do per line
64 {
65 chars += length($0) + 1 # get newline
66 bytes += mbs_length($0) + 1
67 lines++
68 words += NF
69 }
70 END {
71 if (print_total) {
72 if (do_lines)
73 printf "\t%d", tlines
74 if (do_words)
75 printf "\t%d", twords
76 if (do_chars)
77 printf "\t%d", tchars
78 if (do_bytes)
79 printf "\t%d", tbytes
80 print "\ttotal"
81 }
82 }