开发者

Sed on AIX does not recognize -i flag

开发者 https://www.devze.com 2023-03-31 07:26 出处:网络
Does sed -i work on AIX? 开发者_StackOverflow中文版 If not, how can I edit a file \"in place\" on AIX?The -i option is a GNU (non-standard) extension to the sed command.It was not part of the classic

Does sed -i work on AIX?

开发者_StackOverflow中文版

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


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


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


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

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


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.


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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号