Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How would I go about truncating a binary file when a certain pattern is found?

For instance, I want to truncate the file at the first occurrence of the pattern 0xFFFFFFFF.

I think something like awk could do the trick... but I'm not exactly sure how.


share|improve this question
up vote 5 down vote accepted

Convert to octal and assign to the record separator.

awk 'BEGIN{RS="\377\377\377\377"} NR==1 {print;exit}'
share|improve this answer
Perfect, thanks!!! – nico Mar 1 '11 at 14:44

I'm quite sure, it's possible using Perl when you do the following

  • use the command line option -0777 to slurp all the input at once
  • use Latin-1 coding
  • use s/\xFF\xFF\xFF\xFF.*//s

I did something like this a long time ago, but I don't recall the options anymore. For awk I have no idea.

share|improve this answer
Oh, awk is not a requirement, any solution will do. I'm not very good at Perl, could you provide a simple example? – nico Mar 1 '11 at 12:52
Something like perl -0777 -pe 's/\xFF\xFF\xFF\xFF.*//s' < infile > outfile, but I don't know how to set the encoding now. – maaartinus Mar 1 '11 at 13:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.