next up previous 405
Next: Find the position of a substring
Up: String Processing
Previous: String concatenation


Obtain the length of a string

This requires either the wc command in an expression, or the awk function length. Here we determine the number of characters in variable object using both recipes.

     set object = "Processing NGC 2345"
     set nchar = `echo $object | awk '{print length($0)}'`      # = 19
     @ nchar = `echo $object | wc -c` - 1

If the variable is an array, you can either obtain the length of the whole array or just an element. For the whole the number of characters is the length of a space-separated list of the elements. The double quotes are delimiters; they are not part of the string so are not counted.

     set places = ( Jupiter "Eagle Nebula" "Gamma quadrant" )
     set nchara = `echo $places | awk '{print length($0)}'`     # = 35
     set nchar1 = `echo $places[1] | awk '{print length($0)}'`  # =  7
     set nchar2 = `echo $places[2] | awk '{print length($0)}'`  # = 12


next up previous 405
Next: Find the position of a substring
Up: String Processing
Previous: String concatenation

C-shell Cookbook
Starlink Cookbook 4
Malcolm J. Currie
2006 November 26
E-mail:ussc@star.rl.ac.uk

Copyright © 2009 Science and Technology Facilities Council