In AWK, you can read and write files using the `getline` function and file redirection. Here are some commonly used functions and techniques for file handling in AWK:
– **`getline` function:** The `getline` function is used to read a line from a file. The syntax for using `getline` is as follows:
` getline [variable] < "filename"
- `variable` is an optional variable that the line is stored in.
- `"filename"` is the name of the file to read from.
Here is an example of using `getline` in AWK:
` # Read the first line of a file getline line < "file.txt" print line
In this example, we use `getline` to read the first line of the file "file.txt" and store it in the variable `line`.
- **`close` function:** The `close` function is used to close a file that was opened with `getline` or redirection. The syntax for using `close` is as follows:
`
close("filename")
- `"filename"` is the name of the file to close.
Here is an example of using `close` in AWK:
`
# Read lines from two files and print them
getline line1 < "file1.txt"
getline line2 < "file2.txt"
print line1
print line2
close("file1.txt")
close("file2.txt")
In this example, we use `getline` to read lines from two files, print them, and then close the files with `close`.
- **Redirection:** Redirection is a technique where the input and output of an AWK program are redirected to files instead of the console. The syntax for redirection is as follows:
` awk 'program' input_file > output_file
- `program` is the AWK program to run.
- `input_file` is the name of the input file to read from.
- `output_file` is the name of the output file to write to.
Here is an example of using redirection in AWK:
`
# Count the number of lines in a file and write the count to another file
awk 'END {print NR}' input_file > output_file
In this example, we use the AWK program to count the number of lines in the file "input_file" using the built-in variable `NR`. We then redirect the output of the program to the file "output_file".
These are just a few examples of the file handling functions and techniques that you can use in AWK. You can combine these functions with control structures, regular expressions, and other AWK features to read and write files, process large datasets, and perform complex data transformations.