Another solution in sed
, but using less memory:
xxd -c1 -p file |
sed -n -e '1{N;N;N}' -e '/ff\nd8\nff\nd0/{:begin;p;s/.*//;n;bbegin}' -e 'N;D' |
sed -n -e '1{N;N}' -e '/aa\nff\nd9/{p;Q1}' -e 'P;N;D' |
xxd -r -p > new_file
test ${PIPESTATUS[2]} -eq 1 || rm new_file
The 1st sed
prints from ff d8 ff d0
till the end of file. Note that you need as much N
in -e '1{N;N;N}'
as there is bytes in your 1st pattern less one.
The 2nd sed
prints from the beginning of the file to aa ff d9
. Note again that you need as much N
in -e '1{N;N}'
as there is bytes in your 2nd pattern less one.
Again, a test is needed to check if the 2nd pattern is found, and delete the file if it is not.
Note that the Q
command is a GNU extension to sed
. If you do not have it, you need to trash the rest of the file once the pattern is found (in a loop like the 1st sed
, but not printing the file), and check after hex to binary conversion that the new_file end with the wright pattern.