I cannot figure out a way of printing only the odd numbered columns in
a file. I have tried the following:
70s%awk '{for (i=1;i<=NF;i+=2) print $i}' fname
This prints the correct values but each value is put in a new line.
Alternately, if I do:
70s%awk '{for (i=1;i<=NF;i+=2) printf("%.2f ", $i)}' fname
All values are printed in one long line.
Any help will be much appreciated.
Regards,
Sumit
Try something like
awk '{line=""; for (i=1;i<=NF;i+=2) line=line (" " $i); print line;}' fname
-M
awk '{printf (NR%3 ? "%s " : "%s\n"), $i}'
and get the desired output.
Things sometimes look clearer when reformatted.
Your second program:
awk '{for (i=1;i<=NF;i+=2) printf("%.2f ", $i)}' fname
if spread over more than one line:
awk ' {
for (i = 1; i <= NF; i+=2)
printf("%.2f ", $i)
}' fname
It is now imho easier to see that each of these lines needs
to be followed by a newline:
awk ' {
for (i = 1; i <= NF; i+=2)
printf("%.2f ", $i)
print ""
}' fname
or you could even make that its own pattern/action pair:
...
{ print "" }
Which (if you must write a one-liner) you can add to your version:
awk '{for (i=1;i<=NF;i+=2) printf("%.2f ", $i); print ""}' fname
or
awk '{for (i=1;i<=NF;i+=2) printf("%.2f ", $i)} {print ""}' fname
--
John.
You don't even need to do the double-pass approach :
# awk '{for(i=0;i++<NF;++i) printf $i OFS} {print ""}
Or a bit easier to read (and cleaner for non mind-readers ;-) :
# awk '{for (i=1;i<=NF;i+=2) printf $i OFS} {print ""}'
For instance :
$ printf "%s %s %s %s %s %s %s\n" {A..E}{1..7} | \
awk '{for(i=0;i++<NF;++i) printf $i OFS} {print ""}'
A1 A3 A5 A7
B1 B3 B5 B7
C1 C3 C5 C7
D1 D3 D5 D7
E1 E3 E5 E7
In gawk or nawk you can just specify the FS as a RE of
"<spaces><non-spaces><spaces or end of line>" and that'll take out all
the even fields since they'll fit the "non-spaces" part of the pattern,
then just reset $1 to force awk to reconstruct $0, e.g.:
awk -F"[ \t]+[^ \t]+([ \t]+|$)" '{$1=$1}1'
If you only have blank chars (no tabs) in the separators, you can
simplify it to just:
awk -F" +[^ ]+( +|$)" '{$1=$1}1'
In other modern awks you can do the same thing with gsub():
awk '{gsub("[ \t]+[^ \t]+([ \t]+|$)"," ");$1=$1}1'
awk '{gsub(/ +[^ ]+( +|$)/," ");$1=$1}1'
Regards,
Ed.