Sed on AIX does not recognize -i flag

2020-02-01 18:52发布

问题:

Does sed -i work on AIX?

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

回答1:

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



回答2:

#!/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



回答3:

You can simply install GNU version of Unix commands on AIX :

http://www-03.ibm.com/systems/power/software/aix/linux/toolbox/alpha.html



回答4:

You can use a here construction with vi:

vi file >/dev/null 2>&1 <<@
:1,$ s/old/new/g
:wq
@

When you want to do things in the vi-edit mode, you will need an ESC.
For an ESC press CTRL-V ESC.
When you use this in a non-interactive mode, vi can complain about the TERM not set. The solution is adding export TERM=vt100 before calling vi.



回答5:

Another option is to use good old ed, like this:

ed fileToModify <<EOF
,s/^ff/gg/
w
q
EOF


回答6:

you can use perl to do it :

perl -p -i.bak -e 's/old/new/g' test.txt

is going to create a .bak file.



标签: sed aix