Gene
Gene

Reputation: 67

Use AWK to print an adjacent field if a certain value is found in the line of a file

I have the following DATA infile

 Cross,Tim,43560,0000000000,0000000000
 Smith,Sam,00000,4192125555,4192088888
 Williams,Jill,00000,0000000000,4199139999
 Wright,Mark,27645,0000000000,7042964444
 Alston,Jacob,00000,2025674962,0000000000

I need the output to label the corresponding fields if they are populated. The target fields are ZIP, HOME, and WORK which are $3,$4,$5 columns respectively from the infile. If the value of any of the fields is null or 0, then the output field label corresponding will be empty. Here is how the expected output should look:

 Cross,Tim,43560,ZIP,0000000000,,0000000000,
 Smith,Sam,00000,,4192125555,HOME,4192088888,WORK
 Williams,Jill,00000,,0000000000,,4199139999,WORK
 Wright,Mark,27645,ZIP,0000000000,,7042964444,WORK
 Alston,Jacob,00000,,2025674962,HOME,0000000000,

I've attempted to use AWK but can't seem to successfully do an if condition for more than 1 value against the print

code that hasn't worked

zip1=ZIP
home1=HOME
work1=WORK
awk -F ,  '{
        
        if ($3 ~ "00000")
                "'${zip1}'"=="";
        if ($4 ~ "0000000000")
                "'${home1}'"=="";
        if ($5 ~ "0000000000")
                "'${work1}'"=="";

        print $1 "," $2 "," $3 "," "'${zip1}'" "," $4 "," "'${home1}'" "," $5 "," "'${work1}'"}' $inputfile

This code just prints the vars without considering the if statements. If I print directly under 1 if statement, it will only print against that if of course. Not sure how to have the single print recognize each if condition.

Upvotes: 2

Views: 139

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133610

Could you please try following. Using ternary operator in awk here.

awk '
BEGIN{
  FS=OFS=","
}
{
  $3=($3==0?$3 OFS:$3 OFS "ZIP")
  $4=($4==0?$4 OFS:$4 OFS "HOME")
  $5=($5==0?$5 OFS:$5 OFS "WORK")
}
1' Input_file

OR

awk '
BEGIN{
  FS=OFS=","
}
{
  $3=($3 OFS) ($3==0?"":"ZIP")
  $4=($4 OFS) ($4==0?"":"HOME")
  $5=($5 OFS) ($5==0?"":"WORK")
}
1' Input_file

Explanation: Adding detailed explanation for above.

awk '                                ##Starting awk program from here.
BEGIN{                               ##Starting BEGIN section from here.
  FS=OFS=","                         ##Setting field separator and output field separator as comma here.
}
{
  $3=($3==0?$3 OFS:$3 OFS "ZIP")     ##Checking condition if 3rd field is 0 then add OFS to it else add OFS and string ZIP to it.
  $4=($4==0?$4 OFS:$4 OFS "HOME")    ##Checking condition if 4th field is 0 then add OFS to it else add OFS and string HOME to it.
  $5=($5==0?$5 OFS:$5 OFS "WORK")    ##Checking condition if 5th field is 0 then add OFS to it else add OFS and string WORK to it.
}
1                                    ##Will print current line.
' Input_file                         ##Mentioning Input_file name here.                              

Upvotes: 3

Related Questions