Operating System - HP-UX
1835254 Members
2483 Online
110078 Solutions
New Discussion

Re: grouping data using awk

 
SOLVED
Go to solution
N Gopal
Frequent Advisor

grouping data using awk

Hi All,

I am trying to group data present in one variable.


i am using below code:

myoutput=`echo $a | awk '{out=$1;for (k=2;k<=NF;k++){out=sprintf("%s,%s",out,$k);}print out}'`

value of var a is:

1
2
1
2
my output is:

echo $myoutput
1,2,1,2

**************************************
Now here i want to put one condition in awk that:

if $k = 1 then
$out="INTERIM"

if $k = 2 then
$out="PERMANENT"

hence my out put should be like:

echo $myoutput
INTERIM,PERMANENT,INTERIM,PERMANENT

Could some pelase suggest how to make this changes?

Thanks
5 REPLIES 5
Dennis Handly
Acclaimed Contributor
Solution

Re: grouping data using awk

myoutput=$(echo $a | awk '
function trans(ins) {
if (ins == 1)
return "INTERIM"
else if (ins == 2)
return "PERMANENT"
return ins # error case?
}
{
out = trans($1)
for (k=2;k<=NF;k++) {
out=sprintf("%s,%s",out,trans($k))
}
print out
}')
N Gopal
Frequent Advisor

Re: grouping data using awk

Hi Dennis,

Many thanks, It seems that it is working.

One clarification:

in your code what is the use of :
return ins # error case? line
Shall i remove this? Is it have any impact?

Thanks
Dennis Handly
Acclaimed Contributor

Re: grouping data using awk

>in your code what is the use of:
return ins # error case? line
>Shall i remove this? Is it have any impact?

If you want to change "k" only for 1 or 2, you need that assignment to leave it unchanged. So you should change the comment.
N Gopal
Frequent Advisor

Re: grouping data using awk

Hi Dennis,

I am going to use for only 1 or 2. There will be no values other than 1 or 2.

So shall i leave it as it is?

Thanks
Dennis Handly
Acclaimed Contributor

Re: grouping data using awk

>I am going to use for only 1 or 2. There will be no values other than 1 or 2.
>So shall i leave it as it is?

You might as well, even the comment. That suggests how you can extend the function. Otherwise you could optimize it as:
if (ins == 1)
return "INTERIM"
else
return "PERMANENT"