Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect file ends in newline?

Tags:

Over at Can you modify text files when committing to subversion? Grant suggested that I block commits instead.

However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline?

like image 845
grom Avatar asked Sep 02 '08 02:09

grom


People also ask

How do I know if a file is LF or CR 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 find the end of a line file?

Try file -k Short version: file -k somefile. txt will tell you. It will output with CRLF line endings for DOS/Windows line endings. It will output with CR line endings for MAC line endings.

Is every file on New line?

So, it turns out that, according to POSIX, every text file (including Ruby and JavaScript source files) should end with a \n , or “newline” (not “a new line”) character. This acts as the eol , or the “end of line” character. It is a line “terminator”.


2 Answers

@Konrad: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail:

$ cat test_no_newline.txt this file doesn't end in newline$   $ cat test_with_newline.txt this file ends in newline $ 

Though I found that tail has get last byte option. So I modified your script to:

#!/bin/sh c=`tail -c 1 $1` if [ "$c" != "" ]; then     echo "no newline" fi 
like image 147
grom Avatar answered Sep 29 '22 12:09

grom


Here is a useful bash function:

function file_ends_with_newline() {     [[ $(tail -c1 "$1" | wc -l) -gt 0 ]] } 

You can use it like:

if ! file_ends_with_newline myfile.txt then     echo "" >> myfile.txt fi # continue with other stuff that assumes myfile.txt ends with a newline 
like image 43
Steve Kehlet Avatar answered Sep 29 '22 11:09

Steve Kehlet