开发者

Why do I have to specify the -i switch with a backup extension when using ActivePerl?

开发者 https://www.devze.com 2022-12-26 04:10 出处:网络
I cannot get in-place editing Perl one-liners running under ActivePerl to work unless I specify them with a backup extension:

I cannot get in-place editing Perl one-liners running under ActivePerl to work unless I specify them with a backup extension:

C:\> perl -i -ape "splice (@F, 2, 0, q(inserted text)); $_ = qq(@F\n);" file1.txt
Can't do inplace edit without backup.

The same command with -i.开发者_JS百科bak or -i.orig works a treat but creates an unwanted backup file in the process.

Is there a way around this?


This is a Windows/MS-DOS limitation. According to perldiag:

You're on a system such as MS-DOS that gets confused if you try reading from a deleted (but still opened) file. You have to say -i.bak, or some such.

Perl's -i implementation causes it to delete file1.txt while keeping an open handle to it, then re-create the file with the same name. This allows you to 'read' file1.txt even though it has been deleted and is being re-created. Unfortunately, Windows/MS-DOS does not allow you to delete a file that has an open handle attached to it, so this mechanism does not work.

Your best shot is to use -i.bak and then delete the backup file. This at least gives you some protection - for example, you could opt not to delete the backup if perl exits with a non-zero exit code. Something like:

perl -i.bak -ape "splice...." file1.txt && del file1.bak


Sample with recursive modify and delete both done by find. Works on e.g. mingw git bash on windows.

$ find . -name "*.xml" -print0 | xargs -0 perl -p -i.bak -e 's#\s*<property name="blah" value="false" />\s*##g'
$ find . -name "*.bak" -print0 | xargs -0 rm

Binary terminated values passed between find/xargs to handle spaces. Unusual s/ prefix to avoid mangling xml in search term. This assumes you didn't have any .bak files hanging around to begin.

0

精彩评论

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