Skip to Content
Linux in a Nutshell, 6th Edition
book

Linux in a Nutshell, 6th Edition

by Ellen Siever, Stephen Figgins, Robert Love, Arnold Robbins
September 2009
Beginner
942 pages
85h 34m
English
O'Reilly Media, Inc.
Content preview from Linux in a Nutshell, 6th Edition

Variable and Array Assignment

Variables can be assigned a value with an equals sign. For example:

FS = ","

Expressions using the operators +, -, /, and % (modulo) can be assigned to variables.

Arrays can be created with the split( ) function (described later), or they can simply be named in an assignment statement. Array elements can be subscripted with numbers (array[1], ..., array[n]) or with strings. Arrays subscripted by strings are called associative arrays.[9] For example, to count the number of widgets you have, you could use the following script:

/widget/ { count["widget"]++ }        Count widgets
 ND      { print count["widget"] }    Print the count

You can use the special for loop to read all the elements of an associative array:

for (item in array)
    process array[item]

The index of the array is available as item, while the value of an element of the array can be referenced as array[item].

You can use the operator in to test that an element exists by testing to see if its index exists. For example:

if (index in array)
        ...

tests that array[index] exists, but you cannot use it to test the value of the element referenced by array[index].

You can also delete individual elements of the array using the delete statement. (See also the delete entry in Alphabetical Summary of awk Functions and Commands in Alphabetical Summary of awk Functions and Commands.)

[9] In fact, all arrays in awk are associative; numeric subscripts are converted to strings before being used as array subscripts. Associative arrays are ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Unix in a Nutshell, 4th Edition

Unix in a Nutshell, 4th Edition

Arnold Robbins
Linux Under the Hood

Linux Under the Hood

Sander van Vugt
Linux Kernel in a Nutshell

Linux Kernel in a Nutshell

Greg Kroah-Hartman

Publisher Resources

ISBN: 9780596806088Errata Page