Search code examples
shellloopsnewlinedos2unix

for loop / unix2dos to clean a group of files with specific extension


I am trying to use unix2dos on a group of C++ source code files. Basically, unix2dos converts LF to CRLF.

I could simply do the following, and it does what I want :

#!/bin/sh
find . -type f \( -name "*.h" -o -name "*.cpp" \) -exec unix2dos {}\;

but I don't want the file to be modified if it has CRLF end of lines already. That's why I have to modify the script.

#!/bin/sh
for i in `find . -type f \( -name "*.h" -o -name "*.cpp" \)` 
do
  LINE=`file $i | grep CRLF`
  if [ $? -eq 1 ]
  then
    unix2dos $i
  fi
done

The for loop seems a bit tricky to use since spaces are not being handled correctly. When the filename contains space, the shell is trying to apply unix2dos incorrectly on a splited string.

How do I solve the problem ?


Solution

  • Simply change your unix2dos command with the following (provided by putnamhill upper) :

    `perl -wpi -e 's/([^\r])\n/$1\r\n/g' $1`;
    

    Then do your previous find command :

    #!/bin/sh
    find . -type f \( -name "*.h" -o -name "*.cpp" \) -exec unix2dos {}\;
    

    And you are all set.