Home > Net >  perl replace with regex deletes complete file content
perl replace with regex deletes complete file content

Time:08-20

I'm trying to replace a number in a unity file for my automated build process. I've tried different versions of the regexp, as well as commands, however none seem to work correct. I currently have

perl -0777 -ne 'print "${1}0" while /(WebGLSupport\s m_APIs:\s[a-b0-9]{8,16}\s m_Automatic\:\s)1/sg'  ../../CityBotVRSimWebGL/HandTracking/ProjectSettings/ProjectSettings.asset

which correctly prints and replaces the '1'

WebGLSupport
    m_APIs: 0b000000
    m_Automatic: 0

instead of the original

<...>
  - m_BuildTarget: WebGLSupport
    m_APIs: 0b000000
    m_Automatic: 1
<...>

However when I try to do an actual replace the complete content of the file is deleted (not the file itself)

perl -0777 -i -ne 's/(WebGLSupport\s m_APIs:\s[a-b0-9]{8,16}\s m_Automatic\:\s)1/${1}0/'  ../../CityBotVRSimWebGL/HandTracking/ProjectSettings/ProjectSettings.asset

Can anyone tell me what is going wrong. I'm really confused since the regexp seems to be correct. Thanks!

CodePudding user response:

The -i switch says you are doing an inplace edit. However, you use the -n switch to process each line but don't output anything. Perhaps you wanted the -p which outputs the value of $_ (the current "line").

CodePudding user response:

It seems that you want to do a global find and replace on your file. You need -p on the command line and your regex can be simplified.

perl -0777 -i.bak -pe \
's{WebGLSupport\s m_APIs:\s[a-b0-9]{8,16}\s m_Automatic\:\s\K1\b}{0}g; ' \
ProjectSettings.asset

The \K assertion means to keep everything up until that point in the string and don't subject it to replacement. This effectively allows you to "replace this text that is preceded by this other text". No need for parens or captures. The 1 that comes after \K is all that is replaced by the new text, 0.

I added \b after the 1 to indicate that this must be a word boundary. Presumably you don't want to replace other occurrences of WebGLSupport that merely start with a 1. e.g.: m_Automatic: 123.

If the string only occurs once in the file, you can remove the /g flag.

https://perldoc.perl.org/perlrun
https://perldoc.perl.org/perlreref#ANCHORS

  •  Tags:  
  • perl
  • Related