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

I have a binary file with a trailing CRLF (2 bytes total) that I want to remove. How should I do it? Please note that I'm using busybox and I don't have perl.

share|improve this question
Is it trailing each line, or only the end of the file? – bahamat Aug 29 '12 at 15:51
Only at the end of file. Any other CRLF should be ignored. – michelemarcon Aug 30 '12 at 7:26
up vote 3 down vote accepted

With a typical BusyBox installation, I think you're going to have to parse the output of ls to get the size. Once you have the size, extract the first n-2 bytes of the file with head.

size=$(ls -l -- "$file" | awk 'NR==1 {print $5}')
head -c $(($size - 2)) <"$file" >"$file.new"

If you want to truncate the file in place, use dd.

size=$(ls -l -- "$file" | awk 'NR==1 {print $5}')
dd if=/dev/null of="$file" bs=$(($size - 2)) seek=1
share|improve this answer
Rather than parsing ls, busybox often has stat features compiled in. If that's the case here, use size=$(busybox stat -c '%s' "$file") or just size=$(stat -c '%s' "$file") instead. – cas Aug 30 '12 at 2:34
Wouldn't wc -c < "$file" be an easier and safer way to get the file size than parsing ls? Or is wc often left out of busybox? – jw013 Aug 30 '12 at 2:34
@CraigSanders stat is good if it's included, but it isn't always included. I chose commands with a high likelihood of being included. For example, my router doesn't have stat. – Gilles Aug 30 '12 at 2:42
@jw013 wc in BusyBox reads the whole file and counts the bytes (unlike GNU coreutils and IIRC *BSD, which optimize wc <foo and wc foo to read the file size with stat(2)). – Gilles Aug 30 '12 at 2:43
@Gilles Ah, makes sense, thanks. – jw013 Aug 30 '12 at 2:48

Get the size of the file, substract two. You obtain $n and run

dd bs=1 seek=$n < /dev/null of=the-file

Or if you have truncate

truncate  -s -2 the-file
share|improve this answer
He's using busybox so truncate is probably not there. But dd probably is, and I like that solution if there's only one line in the file, or the CFLF is only at the end of the file. – bahamat Aug 29 '12 at 15:53
tr -d '\013' < input > output
share|improve this answer
This would delete all vertical tabs in the file, not a trailing CRLF – Michael Mrozek Aug 30 '12 at 3:24

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.