Skip to Content
Linux Shell Scripting Cookbook - Third Edition
book

Linux Shell Scripting Cookbook - Third Edition

by Clif Flynt, Sarath Lakshman, Shantanu Tushar
May 2017
Beginner
552 pages
28h 47m
English
Packt Publishing
Content preview from Linux Shell Scripting Cookbook - Third Edition

Using loop inside awk

Awk supports a numeric for loop with a syntax similar to C:

    for(i=0;i<10;i++) { print $i ; } 

Awk also supports a list style for loop that will display the contents of an array:

    for(i in array) { print array[i]; } 

The following example shows how to collect data into an array and then display it. This script reads lines from /etc/password, splits them into fields at the : markers, and creates an array of names in which the index is the login ID and the value is the user's name:

    $ awk 'BEGIN {FS=":"} {nam[$1]=$5} END {for {i in nam} \
        {print i,nam[i]}}' /etc/passwd
    root root
    ftp FTP User
    userj Joe User
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

Mastering Linux Shell Scripting - Second Edition

Mastering Linux Shell Scripting - Second Edition

Mokhtar Ebrahim, Andrew Mallett

Publisher Resources

ISBN: 9781785881985