next up previous 405
Next: Changing case
Up: String Processing
Previous: Extracting a substring


Split a string into an array

The awk function split($s$,$a$,sep) splits a string $s$ into an awk array $a$ using the delimiter sep.

     set time = 12:34:56
     set hr = `echo $time | awk '{split($0,a,":"); print a[1]}'` # = 12
     set sec = `echo $time | awk '{split($0,a,":"); print a[3]}'` # = 56

     # = 12 34 56
     set hms = `echo $time | awk '{split($0,a,":"); print a[1], a[2], a[3]}'`
     set hms = `echo $time | awk '{split($0,a,":"); for (i=1; i<=3; i++) print a[i]}'`
     set hms = `echo $time | awk 'BEGIN{FS=":"}{for (i=1; i<=NF; i++) print $i}'`
Variable hms is an array so hms[2] is 34. The last three statements are equivalent, but the last two more convenient for longer arrays. In the second you can specify the start index and number of elements to print. If, however, the number of values can vary and you want all of them to become array elements, then use the final recipe; here you specify the field separator with awk's FS built-in variable, and the number of values with the NF built-in variable.

next up previous 405
Next: Changing case
Up: String Processing
Previous: Extracting a substring

C-shell Cookbook
Starlink Cookbook 4
Malcolm J. Currie
2006 November 26
E-mail:starlink@jiscmail.ac.uk

Copyright © 2013 Science and Technology Facilities Council