next up previous 405
Next: Writing a script within a script
Up: Dealing with Files
Previous: File operators


Creating text files

A frequent feature of scripts is redirecting the output from tasks to a text file. For instance,

     hdstrace $file:r > $file:r.lis
     fitshead $fits > $$.tmp
directs the output of the hdstrace and fitshead to text files. The name of the first is generated from the name of the file whose contents are being listed, so for HDS file cosmic.sdf the trace is stored in cosmic.lis. In the second case, the process identification number is the name of the text file. You can include this special variable to generate the names of temporary files. (The :r is described here.)

If you intend to write more than once to a file you should first create the file with the touch command, and then append output to the file.

     touch logfile.lis
     foreach file (*.sdf)
        echo "FITS headers for $file:r:"  >> logfile.lis
        fitslist $file:r >> logfile.lis
        echo " "
     end
Here we list FITS headers from a series of NDFs to file logfile.lis. There is a heading including the dataset name and blank line between each set of headers. Notice this time we use » to append. If you try to redirect with > to an existing file you'll receive an error message whenever you have the noclobber variable set. >! redirects regardless of noclobber.



There is an alternative--write the text file as part of the script. This is often a better way for longer files. It utilises the cat command to create the file.

   cat >! catpair_par.lis   <<EOF
   ${refndf}.txt
   ${compndf}.TXT
   ${compndf}_match.TXT
   C
   XPOS
   YPOS
   XPOS
   YPOS
   $distance
   `echo $time | awk '{print substr($0,1,5)}'`
   EOF
The above writes the text between the two EOFs to file catpair_par.lis. Note the second EOF must begin in column 1. You can choose the delimiting words; common ones are EOF, FOO. Remember the >! demands that the file be written regardless of whether the file already exists.

A handy feature is that you can embed shell variables, such as refndf and distance in the example. You can also include commands between left quotes (` `); the commands are evaluated before the file is written. However, should you want the special characters $, \, and ` ` to be treated literally insert a \ before the delimiting word or a \ before each special character.



Subsections

next up previous 405
Next: Writing a script within a script
Up: Dealing with Files
Previous: File operators

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