Next: Extension Sample Ord, Previous: Extension Sample Fork, Up: Extension Samples [Contents][Index]
The inplace extension emulates GNU sed’s -i option,
which performs “in-place” editing of each input file.
It uses the bundled inplace.awk include file to invoke the extension
properly:
# inplace --- load and invoke the inplace extension.
@load "inplace"
# Please set INPLACE_SUFFIX to make a backup copy. For example, you may
# want to set INPLACE_SUFFIX to .bak on the command line or in a BEGIN rule.
# N.B. We call inplace_end() in the BEGINFILE and END rules so that any
# actions in an ENDFILE rule will be redirected as expected.
BEGINFILE {
if (_inplace_filename != "")
inplace_end(_inplace_filename, INPLACE_SUFFIX)
inplace_begin(_inplace_filename = FILENAME, INPLACE_SUFFIX)
}
END {
inplace_end(FILENAME, INPLACE_SUFFIX)
}
For each regular file that is processed, the extension redirects
standard output to a temporary file configured to have the same owner
and permissions as the original. After the file has been processed,
the extension restores standard output to its original destination.
If INPLACE_SUFFIX is not an empty string, the original file is
linked to a backup file name created by appending that suffix. Finally,
the temporary file is renamed to the original file name.
The _inplace_filename variable serves to keep track of the
current filename so as to not invoke inplace_end() before
processing the first file.
If any error occurs, the extension issues a fatal error to terminate processing immediately without damaging the original file.
Here are some simple examples:
$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1 file2 file3
To keep a backup copy of the original files, try this:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{ gsub(/foo/, "bar") }
> { print }' file1 file2 file3
Next: Extension Sample Ord, Previous: Extension Sample Fork, Up: Extension Samples [Contents][Index]