next up previous 405
Next: Formatted Printing
Up: String Processing
Previous: Changing case


String substitution

Some implementations of awk offer substitution functions gsub($e$,$s$) and sub($e$,$s$). The latter substitutes the $s$ for the first match with the regular expression $e$ in our supplied text. The former replaces every occurrence.

     set text = "Eta-Aquarid shower"
     # = "Eta-Aquarid stream"
     set text = `echo $text | awk '{sub("shower","stream"); print $0}'` 
     
     # = "Eta-Aquxid strex"
     set text1 = `echo $text | awk '{gsub("a[a-z]","x"); print $0}'`

     # = "Eta-Aquaritt stream"
     set text2 = `echo $text | awk '{sub("a*d","tt"); print $0}'`

     set name = "Abell 3158"
     set catalogue = `echo $name | awk '{sub("[0-9]+",""); print $0}'`  # = Abell
     set short = `echo $name | awk '{gsub("[b-z]",""); print $0}'`      # = "A 3158"

There is also sed.

     set text = `echo $text | sed 's/shower/stream/'`
is equivalent to the first awk example above. Similarly you could replace all occurrences.

     set text1 = `echo $text | sed 's/a[a-z]/x/g'`
is equivalent to the second example. The final g requests that the substitution is applied to all occurrences.

next up previous 405
Next: Formatted Printing
Up: String Processing
Previous: Changing case

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