awk without printing newline

Viewed 218716

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
7 Answers

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 use printf instead.

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.

one way

awk '/^\*\*/{gsub("*","");printf "\n"$0" ";next}{printf $0" "}' to-plot.xls

You can simply use ORS dynamically like this:

awk '{ORS="" ; print($1" "$2" "$3" "$4" "$5" "); ORS="\n"; print($6-=2*$6)}' file_in > file_out

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 newline
print "$_ " prints each line, appending a space
the END{} block is used to print a newline

output: 1 2 3 4 5

Here's the awk way without having to printf and END (assuming your input is less than, say,500 MB):

seq 199 | 

mawk NF=NF RS='^$' FS='\n' OFS= 
123456789101112131415161718192021222324252627282930313233343
536373839404142434445464748495051525354555657585960616263646
566676869707172737475767778798081828384858687888990919293949
596979899100101102103104105106107108109110111112113114115116
117118119120121122123124125126127128129130131132133134135136
137138139140141142143144145146147148149150151152153154155156
157158159160161162163164165166167168169170171172173174175176
177178179180181182183184185186187188189190191192193194195196
197198199

(reformatted for readability - it's one single line, with \n at its end)

And if you simply wanna place a space in between :

seq 19 | 

mawk 'NF && --NF' RS='^$' FS='\n'         
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

if you don't mind 1 extra trailing space, then it's even simpler

mawk NF=NF RS='^$' FS='\n' 
Related