Reputation: 23
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?
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
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
if $2 (column #2) = 11111
set $2="Error"
for $3 to $14 (column #3 to #14) if the column value is <> 11111
$x=$x-$2
if the column value =11111
$x=Error
At the end, the output will still show 14 columns including original #1 column value and converted/calculated new values for column #2 to #14
I have a file (all.cvs) like following:
14 fields
each line may contains a field with a value like "11111" (or any string value)
each column separated by ","
total number of lines is 90
$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
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
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
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