Sample Header Ad - 728x90

Grep command with the side effect of adding a trailing newline character in the last line of file

3 votes
2 answers
543 views
I've been doing some research on how to correctly read lines from a file whose last line may not have a trailing newline character. Have found the answer in [Read a line-oriented file which may not end with a newline](https://unix.stackexchange.com/questions/418060/read-a-line-oriented-file-which-may-not-end-with-a-newline) . However, I have a second goal that is to exclude the comments at the beginning of lines and have found a [grep](http://man7.org/linux/man-pages/man1/grep.1.html) command that achieves the goal $ grep -v '^ *#' file But I have noticed that this command has a (for me unexpected) side behavior: it adds a trailing newline character in the last line if it does not exist
$ cat file
# This is a commentary
aaaaaa
# This is another commentary
bbbbbb
cccccc

$ od -c file
0000000   #       T   h   i   s       i   s       a       c   o   m   m
0000020   e   n   t   a   r   y  \n   a   a   a   a   a   a  \n   #
0000040   T   h   i   s       i   s       a   n   o   t   h   e   r
0000060   c   o   m   m   e   n   t   a   r   y  \n   b   b   b   b   b
0000100   b  \n   c   c   c   c   c   c  \n
0000111

$ truncate -s -1 file

$ od -c file
0000000   #       T   h   i   s       i   s       a       c   o   m   m
0000020   e   n   t   a   r   y  \n   a   a   a   a   a   a  \n   #
0000040   T   h   i   s       i   s       a   n   o   t   h   e   r
0000060   c   o   m   m   e   n   t   a   r   y  \n   b   b   b   b   b
0000100   b  \n   c   c   c   c   c   c
0000110

$ od -c <(grep -v '^ *#' file)
0000000   a   a   a   a   a   a  \n   b   b   b   b   b   b  \n   c   c
0000020   c   c   c   c  \n
0000025
Notice that besides removing the line beginning comments it also adds a trailing newline character in the last line. How could that be?
Asked by Paulo Tom&#233; (3832 rep)
Jan 17, 2020, 06:00 PM
Last activity: Jul 18, 2025, 07:13 AM