Reformating ascii file with awk

Hello,

I've a lot of ascii files that I would like to reformat :

One of files's column (for exemple $5) contains increasing numbers (see exemple) :

$5=

1 
1 
1 
1 
1 
2 
2 
2 
2 
3 
3 
3 
3 
3 
3 
3 
3 
4 
4 

[...]

What I'd like to do is to assign the value "1" for the first record of a consistant block ( a block is defined by the same $5 number), "2" for middle records and "3" for the last one. Then another "1" for the next block, etc. :

In my exemple, the file may become :

$5=

1 
2 
2 
2 
3 
1 
2 
2 
3 
1 
2 
2 
2 
2 
2 
2 
3 
1 
3 

[...]

I've tested some stuff with awk but I always failed...

If you've got some ideas to help me... you're welcome.

Nico.

ps : Please excuse my poor English, I'm from France :slight_smile:

---------- Post updated at 04:23 PM ---------- Previous update was at 04:04 PM ----------

I've tryed this...

awk '{l[NR]=$1};

   	{for(i=1;i<=NR;i++)

	{if(l!=l[i-1])print "1";

	if(l==l[i-1] && l==l[i+1]) print "2";

	if(l!=l[i+1])print "3"}}' toto

but it does not work :confused:

Use gawk, nawk or /usr/xpg4/bin/awk on Solaris:

awk 'BEGIN { ARGV[ARGC++] = ARGV[ARGC-1] }
FNR == NR { _[$5]++ ? max[$5] = NR : min[$5] = NR; next }
{ $5 = FNR == min[$5] ? 1 : (FNR == max[$5] ? 3 : 2) } 5
' infile 

Consecutive default FS characters will be squeezed because of the ricompilation of the record,
let me know if this could be a problem.
With no default FS an OFS should be explicitly specified.

Thanks a lot radoulov..

It perfectly works...

I've tested my ancient script in an Exceed emulated unix... It also works... (whereas it doesn't works on cygwin...) But your solution keeps all the others columns. It's perfect for me.

For the moment I don't understand all the syntax of your script... but I'll try to study a little bit the problem. =)

Caribou.