widged.com
 

Awk Input Output

close(  filename )	close file

getline	Awk provides the function getline to read input from
          the current input file or from a file or pipe. getline
          reads the next input line, splitting it into fields
          according to the settings of NF, NR and FNR. It returns
          1 for success, 0 for end-of-file, and -1 on error. //
          set $0 form next input line, set NF, NR, FNR
getline < file	reads the next input line from the file
          "temp.dat", field splitting is performed, and NF is set. // set $0
          from next input line of file, set NF
getline var	reads the next input line into the user defined
          variable data. No splitting of fields is done and NF is not set.
         // set var from next input line, net NR, FNR
getline var < file	reads the next input line from the file
        "temp.dat" into the user defined variable data, no field
        splitting is done, and NF, NR and FNR are not altered. //
        set var from next input line of file

print	print current input line
print expr-list	print expressions
print expr-list >  file	print expressions to file

Redirecting Output to a File

Everything that we have used GAWK for so far has involved sending the processed data (_output_) to the computer's screen. What happens if we want to save the results of our data processing To do this we need to make use of redirection, indicated by >.

print $1, $2, $3 > "output.txt"

In this example, the results of the GAWK program are saved in a new file called output.txt in the active directory.

Formatted output

sprintf(format,vars)      Format vars to a string
printf fmt, expr-list	format and print
printf fmt, expr-list  >  file	format and print to file

In print and printf above, > > appends to a file, and the | command writes to a pipe. Similarly, command | getline pipes into getline. The function getline returns 0 on the end of a file, -1 on an error.

The statements print and printf are used in awk programs to generate output. awk uses two variables, OFS (output field separator) and ORS (output record separator) to delineate fields and output lines. These can be changed at any time. The special characters used in printf, which follow the % symbol, are,

      c       single character
      d       decimal integer
      e       double number, scientific notation
      f       floating point number
      g       use e or f, whichever is shortest
      o       octal
      s       string
      x       hexadecimal
      %       the % symbol

The default output format is %.6g and is changed by assigning a new value to OFMT.

 
en/computers/lg/awk/input-output.txt · Last modified: 2007/06/03 05:09 (external edit)
 
RSS - Banner by widged, template © 7throot HeadQuarters, 2007