title: Reading character by character with android shell (mksh)
body: <p>Sorry if the question is easy. I am kind of a beginner in shell scripting, and I need to write a script which will work on a text file on a machine which mksh installed, but no working version of sed or most gnu utilities or compatible. </p>
  
  <p>There is also no version of dos2unix installed. </p>
  
  <p>The script receives a file which is dos formatted, but is quite simple in the kind of characters it contains (only letters and numbers, lenght of each line below 20 characters, few than 1000 lines), and it reads the file character by character adding the character to a "line" variable. When it reaches a carriage return it prints the line. Usage will be sh script.sh file.txt > newfile.txt.</p>
  
  <p>The script does not work as intended and I am not really sure why:</p>
  
  <pre><code>#!/bin/sh
  
  riga="";
  
  nomefile="$1";
  
  while IFS='' read -r -n1 carattere; 
      do 
          if [[ $carattere !=  *$'\r'* ]]; then
             riga="${riga}carattere";
          elif [[ $carattere == *$'\r'* ]]; then
              print "${riga%$}";
              riga="";
          fi    
  
  
  
  done &lt; "$nomefile"
  </code></pre>
  
  <p>This is the output of the script as originally written:</p>
  
  <pre><code>caratterecaratterecaratterecaratterecaratterecaratterecaratterecaratterecarattere
  caratterecaratterecaratterecaratterecaratterecaratterecaratterecaratterecarattere
  caratterecaratterecaratterecaratterecaratterecaratterecaratterecaratterecarattere
  caratterecaratterecaratterecaratterecaratterecaratterecaratterecaratterecarattere
  caratterecaratterecaratterecaratterecaratterecaratterecaratterecaratterecarattere
  caratterecaratterecaratterecaratterecaratterecaratterecaratterecaratterecarattere
  caratterecaratterecaratterecaratterecaratterecaratterecaratterecaratterecarattere
  caratterecaratterecaratterecaratterecaratterecaratterecaratterecaratterecarattere
  caratterecaratterecaratterecaratterecaratterecaratterecaratterecaratterecarattere
  </code></pre>
  
  <p>I read the excellent man pages of ksh at <a href="https://www.freebsd.org/cgi/man.cgi?query=ksh" rel="nofollow noreferrer">https://www.freebsd.org/cgi/man.cgi?query=ksh</a> and modified the script as follows:</p>
  
  <pre><code>#!/bin/sh
  
  #!i=0
  #!
  riga="";
  
  nomefile="$1";
  
  while IFS='' read -r -n1 carattere; 
      do 
          if [[ $carattere !=  *$'\r'* ]]; then
             riga="${riga}$carattere";
          elif [[ $carattere == *$'\r'* ]]; then
              print "${riga%$}";
              riga="";
          fi    
  
  
  
  done &lt; "$nomefile"
  </code></pre>
  
  <p>The output is similar to what I intend, but blank lines are inserted between printed lines:</p>
  
  <pre><code>ID
  
  1
  
  2
  
  3
  
  4
  
  5
  
  6
  
  7
  
  8
  </code></pre>