NOTE: this question used to be worded differently, using “with/out newline” instead of “with/out empty line”
I have two files, one with an empty line and one without:
File: text_without_empty_line
$root@kali:/home#cat text_without_empty_line
This is a Testfile
This file does not contain an empty line at the end
$root@kali:/home#
File: text_with_empty_line
$root@kali:/home#cat text_with_empty_line
This is a Testfile
This file does contain an empty line at the end
$root@kali:/home#
Is there a command or function to check if a file has an empty line at the end? I already found this solution, but it does not work for me. (EDIT: IGNORE: A solution with preg_match and PHP would be fine as well.)
To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use an extended regular expression like ' a^ ' or ' $a '.
The empty line in the end of file appears so that standard reading from the input stream will know when to terminate the read, usually returns EOF to indicate that you have reached the end. The majority of languages can handle the EOF marker.
Just type:
cat -e nameofyourfile
If there is a newline it will end with $
symbol.
If not, it will end with a %
symbol.
Olivier Pirson's answer is neater than the one I posted here originally (it also handles empty files correctly). I edited my solution to match his.
In bash:
newline_at_eof()
{
if [[ -s "$1" && -z "$(tail -c 1 "$1")" ]]
then
echo "Newline at end of file!"
else
echo "No newline at end of file!"
fi
}
As a shell script that you can call (paste it into a file, chmod +x <filename>
to make it executable):
#!/bin/bash
if [[ -s "$1" && -z "$(tail -c 1 "$1")" ]]
then
echo "Newline at end of file!"
else
echo "No newline at end of file!"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With