Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Range of fields

Status
Not open for further replies.

butterfm

Programmer
Feb 15, 2002
132
GB
Hi,

Is there a way in awk to print a range of fields without using a for loop ?

e.g. A file contains:

a,b,c,d,e,f,g,h

How can I print fields 3 to 8 without using a for loop to get :

c,d,e,f,g,h

I've done it with a for loop but I get an error saying that the input line is too long.

Thanks,
M.
 
Hi

I searched for such solution too, but nothing found. But the [tt]for[/tt] has to work. Please paste that part of your script and show some sample input too.

Feherke.
 
if on Solaris, try using either /usr/xpg4/bin/awk OR gawk [if you have one].

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Thanks for the replies

The for loop is :

for (i=4; i<NF; i++) printf "%s", $i","; i++; printf "%s", $i"\n"

I can't post the line because it's work sensitive but it would be about 10 lines wrapped round on a terminal window if catted from a file. Is there a limit on the size of teh line in awk.

Also i'm using MKS Toolkit which is a windows based Unix ksh emulator.

Thanks,
Matt.
 
Hi

Strange. As I know, on Linux only the available memory sets the limits. I would try using [tt]print[/tt], which is more resource friendly than [tt]printf[/tt].
Code:
OFS=""
for (i=4; i<NF; i++) print $i ","; print $NF "\n"

Feherke.
 
And this ?
for (i=4; i<NF; ++i) printf "%s,", $i; print $(NF)

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Or this ?
BEGIN {OFS=","}
...
for(i=1; i<=4; ++i) $i=""; x=$0; print x

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
yes, there's a limit for older awk-s - not sure what it's for MKS' awk.
you can try something like this under MKS:
Code:
echo '1,2,3,4,5,7,8,9' | cut -d ',' -f4-

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Code:
BEGIN { FS=OFS=","
  $0 = "1,2,3,4,5,6,7,8,9"
  first = 4
  last = 8
  for (i=1;i<first;i++) $0=substr($0,length($1)+2)
  NF = last - first + 1
  print
}
Output:
[tt]
4,5,6,7,8[/tt]
 
Thanks for all the help guys. Some great advice there. I'll give some of the ideas a go when I get back to work on Monday.

Thanks,
Matt.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top