Solved Delete Carriage Return in the file begins with one

August 17, 2016 at 20:35:40
Specs: linux, 4500
How do I delete carriage return if the file contains carriage in the first line. I want to delete the very first carriage return only if the file begins with one in all files in a folder.


See More: Delete Carriage Return in the file begins with one

Report •

August 18, 2016 at 11:17:12
✔ Best Answer
This korn shell script 1) counts the number of files in testdir 2) determines if all the files start with a ^M and it they do 3) eliminates the first control-M

Keep in mind:
1) I am using Solaris so I use nawk. You may need to use awk
2) Within the nawk scripts where ^M is used that is an actual control-M (or carriage return). Because of this actual control-M (return) key, you may not be able to cut and past this script.

To create an actual control-M in the vi editor, press control-v and then press the return key.
3) change ./testdir to whatever your directory name is. I also wrote the script so it should exist in the directory right above testdir.

4) Make sure the #!/bin/ksh shell invocation is in line 1, column 1 of your script. No comments are allowed above the shell invocation.


# change ./testdir to ./yourdir.  Make sure the script location is one level
# above yourdir
# total number of files in directory
tcnt=$(find "${tdir}" -type f|wc -l)

# find number of files where first line starts with ^M
find "${tdir}" -type f |while read file

   xc=$(nawk ' {
      if( $0 ~ /^^M/)
         print 1 # first line starts with ^M
         print 0
     } ' $file)
   ((fcnt = fcnt + xc))

# if all the files start with ^M
if [[ $tcnt -eq $fcnt ]]
   find "${tdir}" -type f |while read file
      # replace the first ^M of the first line only
      nawk ' {
         if(NR == 1)
         print $0
         } ' "$file" > ./buffile

         # replace the file
         cp ./buffile "$file"

message edited by nails

Report •
Related Solutions

Ask Question