I want the variable sum/NR to be printed side-by-side in each iteration. How do we avoid awk from printing newline in each iteration ? In my code a newline is printed by default in each iteration
for file in cg_c ep_c is_c tau xhpl
printf "\n $file" >> to-plot.xls
for f in 2.54 1.60 800
awk '{sum+=$3}; END {print sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls
done
done
I want the output to appear like this
cg_c ans1 ans2 ans3
ep_c ans1 ans2 ans3
is_c ans1 ans2 ans3
tau ans1 ans2 ans3
xhpl ans1 ans2 ans3
my current out put is like this
**cg_c**
ans1
ans2
ans3
**ep_c**
ans1
ans2
ans3
**is_c**
ans1
ans2
ans3
**tau**
ans1
ans2
ans3
**xhpl**
ans1
ans2
ans3
The ORS (output record separator) variable in AWK defaults to "\n" and is printed after every line. You can change it to " " in the
BEGIN
section if you want everything printed consecutively.I guess many people are entering in this question looking for a way to avoid the new line in
awk
. Thus, I am going to offer a solution to just that, since the answer to the specific context was already solved!In
awk
,print
automatically inserts aORS
after printing.ORS
stands for "output record separator" and defaults to the new line. So whenever you sayprint "hi"
awk prints "hi" + new line.This can be changed in two different ways: using an empty
ORS
or usingprintf
.Using an empty
ORS
This returns "helloman", all together.
The problem here is that not all awks accept setting an empty
ORS
, so you probably have to set another record separator.For example:
Returns "hello-man-".
Using
printf
(preferable)While
print
attachesORS
after the record,printf
does not. Thus,printf "hello"
just prints "hello", nothing else.Finally, note that in general this misses a final new line, so that the shell prompt will be in the same line as the last line of the output. To clean this, use
END {print ""}
so a new line will be printed after all the processing.one way
If Perl is an option, here is a solution using fedorqui's example:
seq 5 | perl -ne 'chomp; print "$_ "; END{print "\n"}'
Explanation:
chomp
removes the newlineprint "$_ "
prints each line, appending a spacethe
END{}
block is used to print a newlineoutput:
1 2 3 4 5
awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls
print
will insert a newline by default. You dont want that to happen, hence useprintf
instead.