Search code examples
awknewlinecmp

Print file without adding trailing newline with awk


I'm using awk to process some program files, removing debugging sections. Some of these files have no trailing newline. I'd like to have awk print the file line by line, with newlines, but without adding an extra newline at the end if it's not present.

E.g.

a
b // no newline after the "b"

is getting turned into this:

a
b<NEWLINE>

The reason that I don't want to add this newline is that I'm trying to use cmp --silent $file $file_without_debug_sections to determine whether to use the original file or the new one. And the reason that I care about that is that I'm trying to limit the number of files that have the debug extension in my compiler output. Only using the non-debug version if it's different also makes it clear which files were changed by this "remove debug sections" process.

So to summarize, how can I get awk to go through the file line by line, but without adding a newline at the end if one doesn't already exist?

My current code looks like this:

{    
    if ($0 ~ /^[ \t]*\/\/[ \t]*\/\*[ \t]*begin[ \t]+debug[ \t]*$/) { 
        print "/* begin debug"; 
    } else if ($0 ~ /^[ \t]*\/\/[ \t]*end[\ t]+debug[\t ]*\*\/[ \t]*$/) { 
        print "end debug */";
    } else print;
}

I tried replacing the print at the end there with printf "%s", $0. But then it instead omits a newline from every line.


Solution

  • You can simply use the fact that awk appends a newline at the end if it is missing, like this:

    # Let's say file1 does not contain a newline at the end. Since
    # awk will add a newline at the end if it is missing, file1_debug
    # WILL contain a newline at the end.
    awk -f remove_debug.awk file1 > file1_debug
    
    # Use awk again before comparing the files, this makes sure that when
    # we compare them, both files have a newline at the end.
    if cmp --silent <(awk '1' file1) <(awk '1' file1_debug) ; then
        echo "The files are the same"
    else
        echo "The files differ"
    fi