0

I have this TXT file that is created by a bash script and at the end I want to remove the last line of that file that is an empty one.

head --lines=-1 r3.txt > r4.txt

sed '$d' r3.txt > r4.txt

cat r3.txt | head -n -1  > r4.txt

r4.txt continues to have the last empty line...

I am on a linux CentOS 6.x server.

Does this have anything to do with line endings (unix x windows)?

Any clues?

Duck
  • 4,674
  • 2
    Are you sure there's an empty line at the end? Note that a correctly formatted Unix text file ends in a linefeed character (because it is a line ending character, not a line separation character, in Unix). What does the end of the output of xxd r3.txt look like? – celtschk Apr 15 '14 at 19:26
  • so, must be this I am seeing. I was thinking that this extra ending character was an empty line. Thanks. Please make that comment an answer. – Duck Apr 15 '14 at 19:29

1 Answers1

1

Probably there is no empty line at the end.

Unix text files consist of lines, each of which ends in a line feed character ('\n', ^J, 0x0a). That is, the linefeed character is not a line separator, but a line ending character. This is especially also true for the last line, and therefore for the file as a whole.

For example, a text file containing

abc
def

will look like this when looked at with xxd:

0000000: 6162 630a 6465 660a                      abc.def.

You can clearly see the single 0a at the end. On the other hand, if there's an additional an empty line at the end, you get

0000000: 6162 630a 6465 660a 0a                   abc.def..

Note that now there are two 0a bytes.

You can also see this with wc -l which counts lines. On the first file, it will give 2, on the second file it will give 3. Note also that if the final line feed is missing (which means the file is not actually a valid text file, although most tools will be able to treat it anyway), wc will only count one line.

celtschk
  • 10,844