Amos
Amos

Reputation: 23

Linux shell awk: displaying different column values when condition met

How can I use both conditional and loop statement inside the awk command to convert a file with special value to a different value like "Error", and not doing any subtraction, instead just display the converted new value like "Error" as the output?

  1. if none of the column value (except column 1 which stays the same in the final output) is equal to the special value like "11111", I use an awk command like following:

    awk -F, '{print $1,$2,($3-$2),($4-$2),($5-$2),($6-$2),($7-$2),($8-$2),($9-$2),($10-$2),($11-$2),($12-$2),($13-$2),($14-$1)} ' all.cvs
    
  2. if the column value = the special value, then no need to do "-$2", just display a new value like "Error"

Basically I want: x means column value for column #2 to #14

I have a file (all.cvs) like following:


$cat all.cvs

A,11111,2,3,4,5,6,7,8,9,10,11,12,13 

B,1,2,3,4,5,6,11111,8,9,10,11,12,13 

C,1,2,3,4,5,6,7,8,9,11111,11,12,13 
....

Upvotes: 1

Views: 1052

Answers (3)

glenn jackman
glenn jackman

Reputation: 246807

awk -F, -v OFS=, -v flag_value=11111 '
  {subtract = $2}
  $2 == flag_value {$2 = "Error"; subtract = 0}
  {
    for (i=3; i<=NF; i++) $i = ($i == flag_value ? "Error" : $i - subtract)
    print
  }
'

Upvotes: 3

beny23
beny23

Reputation: 35018

You could use the following approach:

$ awk -F, '
{ 
  printf("%s", $1); 
  s=($2 != 11111 ? $2 : 0); 
  printf(", %s", ($2 != 11111 ? $2 : "Error")); 
  for (i=3; i<=NF; ++i) 
    printf (", %d", ($i != 11111 ? ($i - s) : "Error")); 
  printf("\n"); 
}' all.csv

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

Put your conditional blocks before your default block. Put next at the end of each in order to resume processing with the next line.

Upvotes: 0

Related Questions