For Programmers: Free Programming Magazines  


Home > Archive > AWK > November 2005 > add a number once per change









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author add a number once per change
ayman_zekry@yahoo.com

2005-11-15, 7:55 am

Hi
i need to add a number -999 only once whenever the first field in a
record changes.
e.g
test1 6556
test1 666776
new 66566
new jjhhhhg


to become


-999 test1 6556
test1 666776
-999 new 66566
new jjhhhhg

can you please help

Thanks

Steffen Schuler

2005-11-15, 7:55 am

ayman_zekry@yahoo.com wrote:
> i need to add a number -999 only once whenever the first field in a
> record changes.
> e.g
> test1 6556
> test1 666776
> new 66566
> new jjhhhhg
>
> to become
>
> -999 test1 6556
> test1 666776
> -999 new 66566
> new jjhhhhg


A working awk script:

#!/usr/bin/awk -f
{ if ($1 == f) {
print " ", $0
} else {
print "-999", $0
f = $1
} }

Regards,

Steffen
ayman_zekry@yahoo.com

2005-11-15, 7:55 am

Works perfectly well.

Thanks alot

Ed Morton

2005-11-15, 6:55 pm

ayman_zekry@yahoo.com wrote:
> Hi
> i need to add a number -999 only once whenever the first field in a
> record changes.
> e.g
> test1 6556
> test1 666776
> new 66566
> new jjhhhhg
>
>
> to become
>
>
> -999 test1 6556
> test1 666776
> -999 new 66566
> new jjhhhhg
>
> can you please help
>
> Thanks
>


You already got this to insert a number at the start of each line where
$1 changes:

awk '$1!=p{n++}{print n,$0;p=$1}' file

How hard is it really to modify that to this:

awk '$1!=p{n="-999"}{print n,$0;p=$1;n=""}' file

or even this if you want keep the spacing consistent:

awk '$1!=p{n="-999"}{print n,$0;p=$1;gsub(/./," ",n)}' file

Maybe I'm just cranky this morning....

Ed.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com