Sed on AIX does not recognize -i flag

rajeev picture rajeev · Aug 29, 2011 · Viewed 28.1k times · Source

Does sed -i work on AIX?

If not, how can I edit a file "in place" on AIX?

Answer

Jonathan Leffler picture Jonathan Leffler · Aug 29, 2011

The -i option is a GNU (non-standard) extension to the sed command. It was not part of the classic interface to sed.

You can't edit in situ directly on AIX. You have to do the equivalent of:

sed 's/this/that/' infile > tmp.$$
mv tmp.$$ infile

You can only process one file at a time like this, whereas the -i option permits you to achieve the result for each of many files in its argument list. The -i option simply packages this sequence of events. It is undoubtedly useful, but it is not standard.

If you script this, you need to consider what happens if the command is interrupted; in particular, you do not want to leave temporary files around. This leads to something like:

tmp=tmp.$$      # Or an alternative mechanism for generating a temporary file name
for file in "$@"
do
    trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
    sed 's/this/that/' $file > $tmp
    trap "" 0 1 2 3 13 15
    mv $tmp $file
done

This removes the temporary file if a signal (HUP, INT, QUIT, PIPE or TERM) occurs while sed is running. Once the sed is complete, it ignores the signals while the mv occurs.

You can still enhance this by doing things such as creating the temporary file in the same directory as the source file, instead of potentially making the file in a wholly different file system.

The other enhancement is to allow the command (sed 's/this/that' in the example) to be specified on the command line. That gets trickier!

You could look up the overwrite (shell) command that Kernighan and Pike describe in their classic book 'The UNIX Programming Environment'.