1. Trang chủ
  2. » Công Nghệ Thông Tin

Red Hat Linux unleashed Second Edition phần 9 pdf

71 345 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 71
Dung lượng 618,89 KB

Nội dung

Motif Programming C HAPTER 26 543 26 MOTIF PROGRAMMING For those of us who like source code or want to build Motif-compliant clients without paying for a distribution, there’s an alternative: LessTif. This is a Motif clone, designed to be compat- ible with Motif 1.2. Distributed under the terms of the GNU GPL, LessTif currently builds 26 different Motif clients (probably many more by the time you read this). You can find a copy of the current LessTif distribution for Linux at http://www.lesstif.org. The current distribution doesn’t require that you use imake or xmkmf, and it comes with shared and static libraries. If you’re a real Motif hacker and you’re interested in the internals of graphical interface construction and widget programming, you should read the details of how LessTif is constructed. You can get a free copy of Harold Albrecht’s book, Inside LessTif, at http:// www.igpm.rwth-aachen.de/~albrecht/hungry.html . For More Information If you’re interested in finding answers to common questions about Motif, read Ken Lee’s Motif FAQ, which is posted regularly to the newsgroup comp.windows.x.motif. Without a doubt, this is the best source of information on getting started with Motif, but it won’t replace a good book on Motif programming. You can find the FAQ on the newsgroup, or at ftp:// ftp.rahul.net/pub/kenton/faqs/Motif-FAQ . An HTML version can be found at http://www.rahul.net/kenton/faqs/Motif-FAQ.html. For information on how to use imake, read Paul DuBois’ Software Portability with imake from O’Reilly & Associates. For Motif 1.2 programming and reference material, read Dan Heller and Paula M. Ferguson’s Motif Programming Manual and Paula M. Ferguson and David Brennan’s Motif Reference Manual, both from O’Reilly & Associates. For the latest news about Motif or CDE, check The Open Group’s site at http:// www.opengroup.org . For the latest information, installation, or programming errata about Red Hat’s Motif distri- bution, see http://www.redhat.com. For the latest binaries of LessTif, programming hints, and a list of Motif 1.2-compatible func- tions and Motif clients that build under the latest LessTif distribution, see http:// www.lesstif.org . For official information on Motif 1.2 from OSF, the following titles (from Prentice-Hall) might help: ■ OSF/Motif Programmers Guide ■ OSF/Motif Programmers Reference Manual ■ OSF/Motif Style Guide Automation, Programming, and Modifying Source Code P ART VI 544 For learning about Xt, you should look at Adrian Nye and Tim O’Reilly’s X Toolkit Intrinsics Programming Manual, Motif Edition, and David Flanagan’s X Toolkit Intrinsics Reference Manual, both from O’Reilly. Other books about Motif include the following: ■ Motif Programming: The Essentials…and More, by Marshall Brain, Digital Press ■ The X Toolkit Cookbook, by Paul E. Kimball, Prentice-Hall, 1995 ■ Building OSF/Motif Applications: A Practical Introduction, by Mark Sebern, Prentice- Hall, 1994 Summary In this chapter, you’ve learned about Motif, a commercial software library add-on for Linux that is available from a number of vendors, including Red Hat Software. Although you’ll have to decide which version of Motif is best for you, hopefully you’ll agree about some of the ben- efits of using Motif to write programs for the X Window System. By following the example program in Listing 26.1, you’ve learned a little about how Motif programs work and how to incorporate some of Motif ’s features into your programs. By using two programming tools included in your Red Hat Linux distribution, imake and xmkmf, you’ve also seen how to save time and effort when writing your own programs for Motif or X11. Finally, in this chapter, I’ve given you some tips on a Motif alternative, LessTif. I hope you’ll explore more topics con- cerning graphical interface programming for X. gawk Programming C HAPTER 27 545 27 GAWK P ROGRAMMING gawk Programming by David B. Horvath, CCP 27 IN THIS CHAPTER ■ Applications 546 ■ Features 547 ■ awk Fundamentals 547 ■ Actions 555 ■ Advanced Input and Output 569 ■ Functions 574 ■ Writing Reports 577 ■ Commands On-the-Fly 579 ■ One Last Built-in Function: system 580 Automation, Programming, and Modifying Source Code P ART VI 546 gawk, or GNU awk, is one of the newer versions of the awk programming language created for UNIX by Alfred V. Aho, Peter J. Weinberger, and Brian W. Kernighan in 1977. The name awk comes from the initials of the creators’ last names. Kernighan was also involved with the creation of the C programming language and UNIX; Aho and Weinberger were involved with the development of UNIX. Because of their backgrounds, you will see many similarities between awk and C. There are several versions of awk: the original awk, nawk, POSIX awk, and of course, gawk. nawk was created in 1985 and is the version described in The awk Programming Language (see the complete reference to this book later in the chapter in the section “Summary”). POSIX awk is defined in the IEEE Standard for Information Technology, Portable Operating System Interface, Part 2: Shell and Utilities Volume 2, ANSI-approved April 5, 1993 (IEEE is the Institute of Electrical and Electronics Engineers, Inc.). GNU awk is based on POSIX awk. The awk language (in all of its versions) is a pattern-matching and processing language with a lot of power. It will search a file (or multiple files) searching for records that match a specified pattern. When a match is found, a specified action is performed. As a programmer, you do not have to worry about opening, looping through the file reading each record, handling end- of-file, or closing it when done. These details are handled automatically for you. It is easy to create short awk programs because of this functionality—many of the details are handled by the language automatically. There are also many functions and built-in features to handle many of the tasks of processing files. Applications There are many possible uses for awk, including extracting data from a file, counting occur- rences of within a file, and creating reports. The basic syntax of the awk language matches the C programming language; if you already know C, you know most of awk. In many ways, awk is an easier version of C because of the way it handles strings and arrays (dynamically). If you do not know C yet, learning awk will make learning C a little easier. awk is also very useful for rapid prototyping or trying out an idea that will be implemented in another language like C. Instead of your having to worry about some of the minute details, the built-in automation takes care of them. You worry about the basic functionality. TIP awk works with text files, not binary. Because binary data can contain values that look like record terminators (newline characters)—or not have any at all—awk will get confused. If you need to process binary files, look into Perl or use a traditional programming language like C. gawk Programming C HAPTER 27 547 27 GAWK P ROGRAMMING Features As is the UNIX environment, awk is flexible, contains predefined variables, automates many of the programming tasks, provides the conventional variables, supports the C-formatted output, and is easy to use. awk lets you combine the best of shell scripts and C programming. There are usually many different ways to perform the same task within awk. Programmers get to decide which method is best suited to their applications. With the built-in variables and functions, many of the normal programming tasks are automatically performed. awk will auto- matically read each record, split it up into fields, and perform type conversions whenever needed. The way a variable is used determines its type—there is no need (or method) to declare vari- ables of any type. Of course, the “normal” C programming constructs like if/else, do/while, for, and while are supported. awk doesn’t support the switch/case construct. It supports C’s printf() for for- matted output and also has a print command for simpler output. awk Fundamentals Unlike some of the other UNIX tools (shell, grep, and so on), awk requires a program (known as an “ awk script”). This program can be as simple as one line or as complex as several thousand lines. (I once developed an awk program that summarizes data at several levels with multiple control breaks; it was just short of 1000 lines.) The awk program can be entered a number of ways—on the command line or in a program file. awk can accept input from a file, piped in from another program, or even directly from the keyboard. Output normally goes to the standard output device, but that can be redirected to a file or piped into another program. Output can also be sent directly to a file instead of standard output. Using awk from the Command Line The simplest way to use awk is to code the program on the command line, accept input from the standard input device (keyboard), and send output to the standard output device (screen). Listing 27.1 shows this in its simplest form; it prints the number of fields in the input record along with that record. Listing 27.1. Simplest use of awk . $ gawk ‘{print NF “: “ $0}’ Now is the time for all Good Americans to come to the Aid of Their Country. Ask not what you can do for awk, but rather what awk can do for you. Ctrl+d continues Automation, Programming, and Modifying Source Code P ART VI 548 6: Now is the time for all 7: Good Americans to come to the Aid 3: of Their Country. 16: Ask not what you can do for awk, but rather what awk can do for you. $ _ NOTE Ctrl+D is one way of showing that you should press (and hold) the Ctrl (or Control) key and then press the D key. This is the default end-of-file key for UNIX. If this doesn’t work on your system, use stty -a to determine which key to press. Another way this action or key is shown on the screen is ^d. The entire awk script is contained within single quotes (‘) to prevent the shell from interpret- ing its contents. This is a requirement of the operating system or shell, not the awk language. NF is a predefined variable that is set to the number of fields on each record. $0 is that record. The individual fields can be referenced as $1, $2, and so on. You can also store your awk script in a file and specify that filename on the command line by using the -f flag. If you do that, you don’t have to contain the program within single quotes. NOTE gawk and other versions of awk that meet the POSIX standard support the specification of multiple programs through the use of multiple -f options. This allows you to execute multiple awk programs on the same input. Personally, I tend to avoid this just because it gets a bit confusing. You can use the normal UNIX shell redirection or just specify the filename on the command line to accept the input from a file instead of the keyboard: gawk ‘{print NF “: “ $0}’ < inputs gawk ‘{print NF “: “ $0}’ inputs Multiple files can be specified by just listing them on the command line as shown in the sec- ond form above—they will be processed in the order specified. Output can be redirected through the normal UNIX shell facilities to send it to a file or pipe it into another program: gawk ‘{print NF “: “ $0}’ > outputs gawk ‘{print NF “: “ $0}’ | more Of course, both input and output can be redirected at the same time. Listing 27.1. continued gawk Programming C HAPTER 27 549 27 GAWK P ROGRAMMING One of the ways I use awk most commonly is to process the output of another command by piping its output into awk. If I wanted to create a custom listing of files that contained the filename and then the permissions only, I would execute a command like: ls -l | gawk ‘{print $NF, “ “, $1}’ $NF is the last field (which is the filename; I am lazy—I didn’t want to count the fields to figure out its number). $1 is the first field. The output of ls -l is piped into awk, which processes it for me. If I put the awk script into a file (named lser.awk) and redirected the output to the printer, I would have a command that looks like: ls -l | gawk -f lser.awk | lp I tend to save my awk scripts with the file type (suffix) of .awk just to make it obvious when I am looking through a directory listing. If the program is longer than about 30 characters, I make a point of saving it because there is no such thing as a “one-time only” program, user request, or personal need. CAUTION If you forget the -f option before a program filename, your program will be treated as if it were data. If you code your awk program on the command line but place it after the name of your data file, it will also be treated as if it were data. What you will get is odd results. See the section “Commands On-the-Fly” later in this chapter for more examples of using awk scripts to process piped data. Patterns and Actions Each awk statement consists of two parts: the pattern and the action. The pattern decides when the action is executed and, of course, the action is what the programmer wants to occur. With- out a pattern, the action is always executed (the pattern can be said to “default to true”). There are two special patterns (also known as blocks): BEGIN and END. The BEGIN code is ex- ecuted before the first record is read from the file and is used to initialize variables and set up things like control breaks. The END code is executed after end-of-file is reached and is used for any cleanup required (like printing final totals on a report). The other patterns are tested for each record read from the file. Automation, Programming, and Modifying Source Code P ART VI 550 The general program format is to put the BEGIN block at the top, any pattern/action pairs, and finally, the END block at the end. This is not a language requirement—it is just the way most people do it (mostly for readability reasons). BEGIN and END blocks are optional; if you use them, you should have a maximum of one each. Don’t code two BEGIN blocks, and don’t code two END blocks. The action is contained within curly braces ( { }) and can consist of one or many statements. If you omit the pattern portion, it defaults to true, which causes the action to be executed for every line in the file. If you omit the action, it defaults to print $0 (print the entire record). The pattern is specified before the action. It can be a regular expression (contained within a pair of slashes [ / /]) that matches part of the input record or an expression that contains com- parison operators. It can also be compound or complex patterns which consists of expressions and regular expressions combined or a range of patterns. Regular Expression Patterns The regular expressions used by awk are similar to those used by grep, egrep, and the UNIX editors ed, ex, and vi. They are the notation used to specify and match strings. A regular ex- pression consists of characters (like the letters A, B, and c—that match themselves in the input) and metacharacters. Metacharacters are characters that have special (meta) meaning; they do not match to themselves but perform some special function. Table 27.1 shows the metacharacters and their behavior. Table 27.1. Regular expression metacharacters in awk . Metacharacter Meaning \ Escape sequence (next character has special meaning, \n is the newline character and \t is the tab). Any escaped metacharacter will match to that character (as if it were not a metacharacter). ^ Starts match at beginning of string. $ Matches at end of string. . Matches any single character. [ABC] Matches any one of A, B, or C. [A-Ca-c] Matches any one of A, B, C, a, b, or c (ranges). [^ABC] Matches any character other than A, B, and C. Desk|Chair Matches any one of Desk or Chair. [ABC][DEF] Concatenation. Matches any one of A, B, or C that is followed by any one of D, E, or F. * [ABC]*—Matches zero or more occurrences of A, B, or C. gawk Programming C HAPTER 27 551 27 GAWK P ROGRAMMING + [ABC]+—Matches one or more occurrences of A, B, or C. ? [ABC]?—Matches to an empty string or any one of A, B, or C. () Combines regular expressions. For example, (Blue|Black)berry matches to Blueberry or Blackberry. All of these can be combined to form complex search strings. Typical search strings can be used to search for specific strings ( Report Date), strings in different formats (may, MAY, May), or as groups of characters (any combination of upper- and lowercase characters that spell out the month of May). These look like the following: /Report Date/ { print “do something” } /(may)|(MAY)|(May)/ { print “do something else” } /[Mm][Aa][Yy]/ { print “do something completely different” } Comparison Operators and Patterns The comparison operators used by awk are similar to those used by C and the UNIX shells. They are the notation used to specify and compare values (including strings). A regular expres- sion alone will match to any portion of the input record. By combining a comparison with a regular expression, specific fields can be tested. Table 27.2 shows the comparison operators and their behavior. Table 27.2. Comparison operators in awk . Operator Meaning == Is equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to != Not equal to ~ Matched by regular expression !~ Not matched by regular expression This enables you to perform specific comparisons on fields instead of the entire record. Re- member that you can also perform them on the entire record by using $0 instead of a specific field. Metacharacter Meaning Automation, Programming, and Modifying Source Code P ART VI 552 Typical search strings can be used to search for a name in the first field (Bob) and compare specific fields with regular expressions: $1 == “Bob” { print “Bob stuff” } $2 ~ /(may)|(MAY)|(May)/ { print “May stuff” } $3 !~ /[Mm][Aa][Yy]/ { print “other May stuff” } Compound Pattern Operators The compound pattern operators used by awk are similar to those used by C and the UNIX shells. They are the notation used to combine other patterns (expressions or regular expres- sions) into a complex form of logic. Table 27.3 shows the compound pattern operators and their behavior. Table 27.3. Compound pattern operators in awk . Operator Meaning && Logical AND || Logical OR ! Logical NOT () Parentheses—used to group compound statements If I wanted to execute some action (print a special message, for instance), if the first field con- tained the value “Bob” and the fourth field contained the value “Street”, I could use a com- pound pattern that looks like: $1 == “Bob” && $4 == “Street” {print”some message”} Range Pattern Operators The range pattern is slightly more complex than the other types—it is set true when the first pattern is matched and remains true until the second pattern becomes true. The catch is that the file needs to be sorted on the fields that the range pattern matches. Otherwise, it might be set true prematurely or end early. The individual patterns in a range pattern are separated by a comma ( ,). If you have twenty-six files in your directory with the names A to Z, you can show a range of the files as shown in Listing 27.2. Listing 27.2. Range pattern example. $ ls | gawk ‘{$1 == “B”, $1 == “D”}’ B C D [...]... remember is that the pattern is done when the second condition is true The second gawk command only shows the B because C is less than or equal to D (making the second condition true) The third gawk shows B through E because E is the first one that is greater than D (making the second condition true) 554 Automation, Programming, and Modifying Source Code PART VI The first field is $1, the second is $2,... save data That is done through the use of variables Within awk, there are three types of variables: field, predefined, and user-defined You have already seen examples of the first two—$1 is the field variable that contains the first field in the input record, and FS is the predefined variable that contains the field separator 556 Automation, Programming, and Modifying Source Code PART VI predefined... is stored in a single-dimension array with the subscript actually stored in the form 5 SUBSEP 3 The predefined variable SUBSEP contains the value of the separator of the subscript components It defaults to the double quote (“ or \034) because it is unlikely that the double quote will appear in the subscript itself Remember that the double quotes are used to contain a string; they are not stored as... the current input file It is reset for each file that is specified on the command line It always contains a value that is less than or equal to the variable NR The character that is used to separate fields is stored in the variable FS with a default value of space You can change this variable with a command-line option or within your program If you know that your file will have some character other than... from the database into a file that is then manipulated by an awk script to produce the exact format required When required, an awk script can even create the SQL statements used to query the database (specifying the key values for the rows to select) The following example is used when the query tool places a space before a numeric field that must be removed for program that will use the data in another... will cause other predefined variables to change If your original input record had two fields and you set $3=”third one”, then NF would be changed from 2 to 3 Strings supports two general types of variables: numeric (which can consist of the characters 0 through 9, + or -, and the decimal [.]) and character (which can contain any character) Variables awk gawk Programming CHAPTER 27 5 59 that contain characters... versions of awk don’t support all these functions GAWK “UNIX Unleashed, Second Edition 27 PROGRAMMING A string constant is always enclosed within the double quotes (“”) and can be from zero (an empty string) to many characters long The exact maximum varies by version of UNIX; personally, I have never hit the maximum The double quotes aren’t stored in memory A typical string constant might look like the... conversion Special String Constants awk supports special string constants that cannot be entered from the keyboard or have special meaning If you wanted to have a double quote (“) character as a string constant (x = “””), how would you prevent awk from thinking the second one (the one you really want) is the end GAWK split(“08/12/ 196 2”, results, “/”); 27 PROGRAMMING The split(string, store, delim) function... expect Predefined Variables provides you with a number of predefined (also known as built-in) variables These are used to provide useful data to your program; they can also be used to change the default behavior of the gawk (by setting them to a specific value) gawk Table 27.4 summarizes the predefined variables in gawk Earlier versions of awk don’t support all these variables Table 27.4 gawk predefined... thing about awk printf is that it uses syntax that is very similar to the printf() function in C The general format of the awk printf is as follows (the parentheses are only required if a relational expression is included): printf format-specifier, variable1,variable2, variable3, variablen printf(format-specifier, variable1,variable2, variable3, variablen) Personally, I use the second form because I am . about Red Hat s Motif distri- bution, see http://www.redhat.com. For the latest binaries of LessTif, programming hints, and a list of Motif 1.2-compatible func- tions and Motif clients that build. Cookbook, by Paul E. Kimball, Prentice-Hall, 199 5 ■ Building OSF/Motif Applications: A Practical Introduction, by Mark Sebern, Prentice- Hall, 199 4 Summary In this chapter, you’ve learned about. you’ve learned about Motif, a commercial software library add-on for Linux that is available from a number of vendors, including Red Hat Software. Although you’ll have to decide which version of Motif

Ngày đăng: 13/08/2014, 02:22

TỪ KHÓA LIÊN QUAN