In AWK, you can reformat text by manipulating fields, lines, and files using a combination of built-in variables, functions, and control structures. Here are some commonly used techniques for reformatting text in AWK: - **Field manipulation:** You can manipulate fields (columns) in a line using the built-in variables `$1`, `$2`, etc., and the `NF` variable. Here are some commonly used field-related functions: - `gsub`: Global substitution of a regular expression with a replacement string. - `substr`: Returns a substring of a string. - `sprintf`: Formats a string using a template. Here is an example of using field manipulation in AWK to reformat text:
` # Convert a CSV file to a tab-separated file with the first and third fields only BEGIN { FS = "," OFS = "\t" } { print $1, $3 }
“
In this example, we use the `FS` and `OFS` variables to set the input and output field separators, respectively. We then use the `print` statement to print only the first and third fields of each line, separated by a tab.
– **Line manipulation:** You can manipulate lines using the built-in variables `NR` and `FNR`, as well as the `getline` function. Here are some commonly used line-related functions:
– `print`:Prints one or more strings or variables, followed by the output record separator (`ORS`).
– `getline`: Reads the next input line into a variable.
Here is an example of using line manipulation in AWK to reformat text:
# Print every other line of a file
{
if (NR % 2 == 1) {
print
}
}
In this example, we use the `if` statement to check if the line number (`NR`) is odd, and if so, we use the `print` statement to print the line.
– **File manipulation:** You can manipulate files using the `getline` function and file redirection. Here are some commonly used file-related functions:
– `getline`: Reads the next input line into a variable.
– `close`: Closes an open file.
Here is an example of using file manipulation in AWK to reformat text:
# Convert a tab-separated file to a CSV file
BEGIN {
FS = “\t”
OFS = “,”
}
{
gsub(/”/, “\”\””, $0)
print “\”” $0 “\””
}
In this example, we use the `gsub` function to replace all occurrences of double quotes (`”`) with two double quotes (`””`) in each line. We then use the `print` statement to enclose the entire line in double quotes, separated by commas. This effectively converts a tab-separated file to a CSV file.
These are just a few examples of the techniques that you can use in AWK to reformat text. You can combine these techniques with other AWK features to implement complex text processing and manipulation tasks.