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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

awk if condition 2

Status
Not open for further replies.

arunrr

Programmer
Oct 2, 2009
103
US
Hello,

I need to modify the 3rd field (FS=,) of the file...

1,B Lee,4,0,38,0,9.50
2,IK Pathan,3.6,0,29,3,7.25
3,L Ablish,2,0,17,2,8.50
4,PP Chawla,4,0,24,3,6.00
5,Y Singh,2,0,15,0,7.50
6,RR Powar,4,0,28,0,7.00

as below...

3.0 to 3
3.6 to 4
3.* no change

If i only had field three as input, i used the following...

awk -F. '{if ($2==0 || $2==6) printf ("%.0f",$0); else printf $0}'

Need help when the entire file is the input.

Thanks
Arun
 
You may use the split function.

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Thanks FH,

Here is what i did...

awk -F, -vOFS=',' 'split($3,a,"."); {if (a[2]==0) $3=a[1]; if (a[2]==6) $3=a[1]+1}1' "INPUTFILE"

Only problem is is get the input along with the output. How can I suppress the input?

Thanks
AR
 
Hi

AR said:
Only problem is is get the input along with the output.
man awk said:
An AWK program consists of a sequence of pattern-action statements and
optional function definitions.

pattern { action statements }

The pattern comes first, and then the
action. Action statements are enclosed in { and }. Either the pattern
may be missing, or the action may be missing, but, of course, not both.
[highlight]If the pattern is missing, the action is executed for every single[/highlight]
[highlight]record of input. A missing action is equivalent to[/highlight]

[highlight]{ print }[/highlight]

[highlight]which prints the entire record.[/highlight]
In your code there are two occurrences of pattern without action, so in two cases will the current record be printed out :
Code:
awk -F, -vOFS=',' '[highlight]split($3,a,".")[/highlight]; {if (a[2]==0) $3=a[1]; if (a[2]==6) $3=a[1]+1}[highlight]1[/highlight]' "INPUTFILE"
So the solution is to transform the first pattern into action statement. I mean, enclose it in braces ( {} ).

Feherke.
 
Hi Feherke,

Done. Here is the final code...

awk -F, -vOFS=',' '{split($3,a,"."); if (a[2]==0) $3=a[1]; if (a[2]==6) $3=a[1]+1}1'

Thanks,
Arun
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top