Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check end-of-line of a text file to see if it is unix or dos format?

I need to convert the text file to dos format (ending each line with 0x0d0x0a, rather than 0x0a only), if the file is in unix format (0x0a only at the end of each line).

I know how to convert it (sed 's/$/^M/'), but don't how how to detect the end-of-line character(s) of a file.

I am using ksh.

Any help would be appreciated.

[Update]: Kind of figured it out, and here is my ksh script to do the check.

[qiangxu@host:/my/folder]# cat eol_check.ksh
#!/usr/bin/ksh

if ! head -1 $1 |grep ^M$ >/dev/null 2>&1; then
  echo UNIX
else
  echo DOS
fi

In the above script, ^M should be inserted in vi with Ctrl-V and Ctrl-M.

Want to know if there is any better method.

like image 913
Qiang Xu Avatar asked Aug 06 '13 15:08

Qiang Xu


People also ask

How can I tell if a file is CRLF or LF?

use a text editor like notepad++ that can help you with understanding the line ends. It will show you the line end formats used as either Unix(LF) or Macintosh(CR) or Windows(CR LF) on the task bar of the tool. you can also go to View->Show Symbol->Show End Of Line to display the line ends as LF/ CR LF/CR.

How do you read the last line of a file in Unix?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.


1 Answers

Simply use the file command. If the file contains lines with CR LF at the end, this is printed out by a comment: 'ASCII text, with CRLF line terminators'.

e.g.

if file  myFile | grep "CRLF"  > /dev/null 2>&1;
  then
  ....
fi
like image 149
tue Avatar answered Jan 04 '23 01:01

tue