简体   繁体   English

替换最后出现的 HEX 文件 - Perl 正则表达式

[英]Replace last occurrence of an HEX file - Perl Regex

I'm building a script in bash that edits a binary file.我正在 bash 中构建一个编辑二进制文件的脚本。 I managed how to achieve first occurrence replace and all occurrences replace but i cannot manage how to replace the last occurrence.我管理了如何实现第一次出现替换和所有出现替换,但我无法管理如何替换最后一次出现。

The script has to replace F8 byte with F0.脚本必须用 F0 替换 F8 字节。

This is the code for ALL and FIRST:这是 ALL 和 FIRST 的代码:

ALL全部

perl -pe 's/\x{F8}/\x{F0}/g' < CS.midi > CSnew.midi 

FIRST第一的

perl -pe 's/\x{F8}/\x{F0}/' < CS.midi > CSnew.midi 

Any suggestions for replace the last occurrence of F8?关于替换最后一次出现的 F8 有什么建议吗?

Using regular expressions isn't even needed:甚至不需要使用正则表达式:

perl -0777 -pe 'substr $_, rindex($_, "\xF8"), 1, "\xF0"' CS.midi > CSnew.midi

reads the entire file, and replaces the last occurrence of the matching byte.读取整个文件,并替换最后出现的匹配字节。

First of all, your code to change the first is incorrect.首先,您更改第一个的代码不正确。 You are reading the file a line at a time, and it changes the first of each line .您一次读取一行文件,它会更改每行的第一行 This means is changes the first, and the first after each LF (0x0A).这意味着更改第一个,以及每个 LF (0x0A) 之后的第一个。

-0777 will cause the entire file to be treated as one line. -0777将导致整个文件被视为一行。

perl -0777pe's/\xF8/\xF0/g'        # All
perl -0777pe's/\xF8/\xF0/'         # First
perl -0777pe's/^.*\K\xF8/\xF0/s'   # Last

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM