How can I determine line endings in an embedded environment?

208 views Asked by At

How can I determine the line endings of a text file using the busybox version of commands?

My goal: to list files in a directory and whether they have DOS line endings or UNIX line endings. I'd ideally like to do this in some sort of loop like this:

for i in *; do
    **determineEndings** $i
done

or

find . -type f | **determineEndings**

Unfortunately, since I have the busybox version of commands, I don't have the file command available to help me out. I found a binary of file for my target system and copied the magic file to where file --version tells me to, but still get the following error:

$ file -d myfile.txt
unknown, 0: Warning: using regular magic file `/usr/share/misc/magic'
file: could not find any valid magic files!

I can compile C code for the target environment so simple C code I could compile to binary for the target system would work too.

1

There are 1 answers

0
TrentP On

Give this a try:

grep -q `echo -e '\015'` $i && echo DOS

The echo command will produce a CR-LF pair, and then grep will search for those exact characters, finding them in DOS text file. I've tested this with busybox echo and grep and it worked. It's possible a different version of busybox with different features compiled in might not work.

A file with mixed line endings will be detected as DOS. You could use -c to get a count of CR-LF pairs and then compare to total lines with wc -l if you want to determine if how many DOS endings vs how many UNIX endings it has.

If you have binary files, you'll have to determine if the file is text or binary another way.