rpgtiger
rpgtiger

Reputation: 13

bash script using awk - printing unwanted newline?

I'm writing a bash script for a class assignment, and I'm getting some very strange behavior from awk. It seems like it's writing two newlines for a single \n character. Here's the part of the code in question:

iterate () {
    for (( i=0; i<$2; i++ )); do
        echo -n $(date +%H:%M:%S) >> cpu_usage.plot
        echo -n $(date +%H:%M:%S) >> disk_usage.plot
        mpstat | awk 'NR>3 { printf "\t"$4"\t"$6"\t"$13"\n" }' >> cpu_usage.plot
        iostat | awk 'NR>6 { printf "\t"$3"\t"$4"\n" }' >> disk_usage.plot
        sleep $1
    done
}

The output for cpu_usage.plot is fine, but the output for disk_usage.plot is wrong. It's printing one newline too many between each iteration.

Relevant lines from cpu_usage.plot after execution:

17:33:28    0.64    0.02    99.33
17:33:30    0.64    0.02    99.33
17:33:32    0.64    0.02    99.33
17:33:34    0.64    0.02    99.33

And from disk_usage.plot:

17:33:28    2.16    50.90

17:33:30    2.16    50.90

17:33:32    2.16    50.90

17:33:34    2.16    50.90

I would normally think this was an issue with it picking up an extra newline from iostat or something, but that doesn't seem to be the case. Changing line 6 to:

iostat | awk 'NR>6 { printf "\t"$3"\t"$4 }' >> disk_usage.plot # removing the "\n"

doesn't print any newlines at all; the whole thing is on one line. Messing with the conditional for what lines to grab tends to break things further, and with NR>6 it grabs the correct data, anyway.

It's really bizarre to me that both commands are pretty much identical, other than its input and where it sends the output, but one does it correctly and the other does not. A search of StackOverflow yielded this, which I thought might be helpful, but they appear to have been having a different issue. I admit that I'm brand new to awk, but I'm totally at a loss here. Anyone have any ideas?

Upvotes: 0

Views: 1003

Answers (1)

Cyrus
Cyrus

Reputation: 88563

iostat outputs one trailing empty line. I suggest:

iostat | awk 'NR>6 && $0 != "" { printf "\t"$3"\t"$4"\n" }' >> disk_usage.plot

or

iostat | awk 'NR>6 && $0 != "" { print "\t"$3"\t"$4 }' >> disk_usage.plot

Upvotes: 1

Related Questions