This prints fields 1-3 and 31-last in one line:
awk '
{
for (i=1; i<=3; i++)
printf "%s%s", $i, OFS
for (i=31; i<=NF; i++)
printf "%s%s", $i, OFS
printf "%s", ORS
}'
Notes:
- I don't separate fields with explicit space, I use
OFS
. The default value of OFS
is a space.
- I don't separate records with explicit newline, I use
ORS
. The default value of ORS
is a newline.
It's good practice to use such standard awk
variables. If you ever need non-default values, you won't need to change the code (e.g. awk -v OFS=- …
).
The above code is quite simple but you may or may not like its "policy" regarding OFS
s: the first for
loop will always generate exactly 3 OFS
s, even if the input line is empty; and there will always be at least one trailing OFS
.
The following variant avoids extra OFS
s:
awk '
{
for (i=1; i<=3 && i<=NF; i++)
printf "%s%s", (i==1)? "" : OFS, $i
for (i=31; i<=NF; i++)
printf "%s%s", OFS, $i
printf "%s", ORS
}'
Tricks in use:
- The additional condition
i<=NF
in the first for
loop makes it not print OFS
s for fields that don't exist in the input.
- Instead of printing
OFS
after a field and trying to suppress the last (trailing) one, we print OFS
before a field and suppress it for the first field that gets printed. The point is it's easy to tell which field will be printed as the first in the output (even if NF
may vary); it's not so easy to tell which field will be printed as the last (if NF
may vary).
On the other hand your example code ({print $1,$2,$3,$31,$32,$33,$34,$35,$36,$37}
) prints 10 fields and exactly 9 OFS
s between them, even if the input line is empty. I don't know if this is what you need. There is no trailing OFS
after the last field printed. To achieve something similar, try this:
awk '
{
for (i=1; i<=3; i++)
printf "%s%s", (i==1)? "" : OFS, $i
for (i=31; i<=NF || i<=37; i++)
printf "%s%s", OFS, $i
printf "%s", ORS
}'
If there are 37 or less fields in the input then there will be exactly 9 OFS
s; this will behave like your code. Additional fields (38th and further) will generate more OFS
s and fields in the output.