Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed on AIX does not recognize -i flag

Tags:

aix

sed

Does sed -i work on AIX?

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

like image 463
rajeev Avatar asked Aug 29 '11 16:08

rajeev


2 Answers

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'.

like image 183
Jonathan Leffler Avatar answered Oct 18 '22 22:10

Jonathan Leffler


#!/bin/ksh
host_name=$1
perl -pi -e "s/#workerid#/$host_name/g" test.conf 

Above will replace #workerid# to $host_name inside test.conf

like image 37
Gavin Lee Avatar answered Oct 18 '22 20:10

Gavin Lee