Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print file without adding trailing newline with awk

Tags:

newline

awk

cmp

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.

like image 394
Chris Middleton Avatar asked Sep 07 '25 22:09

Chris Middleton


2 Answers

Change your print line statements to printf "%s%s", line, RT

For example

$ seq 3 > s3
$ head -c -1 s3 > s3nn                      # remove last newline
$ awk '$1=$1{printf "%s%s", $0, RT}' s3nn
1
2
3$ awk '$1=$1' s3nn
1
2
3
$ cat s3nn
1
2
3$

in your case print without arguments is equal to print $0

like image 100
karakfa Avatar answered Sep 11 '25 01:09

karakfa


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
like image 41
hek2mgl Avatar answered Sep 11 '25 00:09

hek2mgl