I am trying to use Perl's in-place-editing feature to change some text in files with Unix line endings in a PowerShell session on Windows:
perl.exe -i'.bak' -p -e "s#PATTERN#REPLACEMENT#g" (get-childItem *.sql,*/*.sql)
Unfortunately, the line endings are changed from Unix to Windows.
Is there an option to tweak this one liner so that it doesn't modify the line endings?
CodePudding user response:
Normally, on Windows, the :crlf
PerlIO layer is used by default, which converts to and from CRLF line endings in the file to LF in the strings perl
sees. Traditionally, the :raw
PerlIO layer would be used to prevent this, but according to the documentation:
If you want UNIX line endings on a platform that normally does CRLF translation, but still want UTF-8 or encoding defaults, the appropriate thing to do is to add
:perlio
to the PERLIO environment variable, or open the handle explicitly with that layer, to replace the platform default of:crlf
.
You can use the open
pragma to change the default layers for opening files (And/or use the three argument version of open
to customize them on a per-file basis).
In my testing (using Strawberry Perl 5.32), using :perlio
with that pragma still did line ending conversion despite the above, so :raw
it is. (However, perlio
works with the PERLIO
environment variable. It looks like when set that way it replaces the default layers, when used with the pragma it appends to the defaults instead despite what the documentation suggests.)
So,
PS> perl.exe -Mopen="IO,:raw" -i'.bak' -p -e "s#PATTERN#REPLACEMENT#g" (get-childItem *.sql,*/*.sql)
or
PS> $env:PERLIO="perlio"
PS> perl.exe -i'.bak' -p -e "s#PATTERN#REPLACEMENT#g" (get-childItem *.sql,*/*.sql)