Batch Dos2Unix

2019-07-27

Tags:
  • bash
Categories:
  • howto

Problem

You just inherited a project with many files containing CRLF line endings.

You want them all with LF.

You don't care about diff showing that the entire file has changed.

Solution

One line

for inputFile in $(find . -type f); do if [ $(file $inputFile | grep -c 'with CRLF line terminators') -eq 1 ]; then dos2unix $inputFile; fi; done

Multiple lines

#!/bin/bash

for inputFile in $(find . -type f)
do
	if [ $(file $inputFile | grep -c 'with CRLF line terminators') -eq 1 ]
	then
		dos2unix $inputFile
	fi
done

What does this mean?

  • find . -type f finds all files in the current directory (recursively).
  • file $inputFile describes the kind of file we have and may show an output such as:
    HTML document, ASCII text, with CRLF line terminators
    
  • grep -c counts how many times a pattern is matched
  • dos2unix translates the line endings in the file