home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


11.7 User-Defined Functions

nawk allows you to define your own functions. This makes it easy to encapsulate sequences of steps that need to be repeated into a single place, and reuse the code from anywhere in your program. Note: for user-defined functions, no space is allowed between the function name and the left parenthesis when the function is called.

The following function capitalizes each word in a string. It has one parameter, named input , and five local variables, which are written as extra parameters.

# capitalize each word in a string
function capitalize(input,    result, words, n, i, w)
{
	result = ""
	n = split(input, words, " ")
	for (i = 1; i <= n; i++) {
		w = words[i]
		w = toupper(substr(w, 1, 1)) substr(w, 2)
		if (i > 1)
			result = result " "
		result = result w
	}
	return result
}

# main program, for testing
{ print capitalize($0) }

With this input data:

A test line with words and numbers like 12 on it.

This program produces:

A Test Line With Words And Numbers Like 12 On It.


Previous: 11.6 Variables and Array Assignments UNIX in a Nutshell: System V Edition Next: 11.8 Group Listing of awk Functions and Commands
11.6 Variables and Array Assignments Book Index 11.8 Group Listing of awk Functions and Commands

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System