Alternative to `sed -i` on Solaris

我是研究僧i 提交于 2019-12-17 04:05:07

问题


On Linux sed -i will modify the input files in place. It doesn't work on Solaris, though.

sed -i '$ s/OLD/NEW/g' test        
sed: illegal option -- i

What can I use in place of sed -i on Solaris?


回答1:


You'll need to replicate -i's behavior yourself by storing the results in a temp file and then replacing the original file with the temp file. This may seem inelegant but that's all sed -i is doing under the covers.

sed '$ s/OLD/NEW/g' test > test.tmp && cat test.tmp > test && rm test.tmp

If you care you could make it a bit more robust by using mktemp:

tmp=$(mktemp test.XXXXXX)
sed '$ s/OLD/NEW/g' test > "$tmp" && cat "$tmp" > test && rm "$tmp"



回答2:


It isn't exactly the same as sed -i, but i had a similar issue. You can do this using perl:

perl -pi -e 's/find/replace/g' file

doing the copy/move only works for single files. if you want to replace some text across every file in a directory and sub-directories, you need something which does it in place. you can do this with perl and find:

find . -exec perl -pi -e 's/find/replace/g' '{}' \;



回答3:


One more "one-line" command which works on Solaris 11 host in bash enviroment:

for i in `cat strings_to_delete.txt`
do 
    sed "/$i/d" file.to_edit.txt > file.edited.txt &&
        mv file.edited.txt file.to_edit.txt
done

It deletes strings from file strings_to_delete.txt in file.to_edit.txt. File strings_to_delete.txt contains multiple lines with one string per line.



来源:https://stackoverflow.com/questions/3576380/alternative-to-sed-i-on-solaris

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!