Next: , Previous: , Up: Extension Samples   [Contents][Index]

16.7.4 Enabling In-Place File Editing

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.

    inplace_begin(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 filename created by appending that suffix. Finally, the temporary file is renamed to the original filename.

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

We leave it as an exercise to write a wrapper script that presents an interface similar to ‘sed -i’.