One method uses the awk function substr(
,
,
). This
returns the substring from string
starting from character position
up to a maximum length of
characters. If
is not supplied,
the rest of the string from
is returned. Let's see it in action.
set caption = "Processing NGC 2345."
set object = `echo $caption | awk '{print substr($0,12,8)}'` # = "NGC 2345"
set objec_ = `echo $caption | awk '{print substr($0,16)}'` # = "2345."
set places = ( Jupiter "Eagle Nebula" "Gamma quadrant" )
set oba = `echo $places | awk '{print substr($0,28,4)}'` # = "quad"
set ob1 = `echo $places[3] | awk '{print substr($0,7)}'` # = "quadrant"
An array of strings is treated as a space-separated list of the elements.
The double quotes are delimiters; they are not part of the string so
are not counted.
Another method uses the UNIX cut command. It too can specify a range or ranges of characters. It can also extract fields separated by nominated characters. Here are some examples using the same values for the array places
set cut1 = `echo $places | cut -d ' ' -f1,3` # = "Jupiter Nebula"
set cut2 = `echo $places[3] | cut -d a -f2` # = "mm"
set cut3 = `echo $places | cut -c3,11` # = "pg"
set cut4 = `echo $places | cut -c3-11` # = "piter Eag"
set cut5 = `cut -d ' ' -f1,3-5 table.dat` # Extracts fields 1,3,4,5
# from file table.dat
The -d qualifier specifies the delimiter between associated data (otherwise called fields). Note the the space delimiter must be quoted. The -f qualifier selects the fields. You can also select character columns with the -c qualifier. Both -c and -f can comprise a comma-separated list of individual values and/or ranges of values separated by a hyphen. As you might expect, cut can take its input from files too.
C-shell Cookbook