1

Hi I have a text file that look like this

P383      0         II-5    2     0     1/2   0       0       42.7    0       54.67   0      
T528      0         P383    2     0     1/2   0       0       0       0       34.06   0      
T529      III-8     0       2     0     0     0       0       0       0       37.74   0      
T530      III-8     0       2     0     0     0       0       0       0       36.73   0      
3B888     III-4     III-5   2     0     1/2   38.4    0       0       0       44.38   0      

I want to replace the 0 in columns 2, 3 and 5 with " " (a blank), I know how to do it for one column

The desired output would be

P383                II-5    2           1/2   0       0       42.7    0       54.67   0      
T528                P383    2           1/2   0       0       0       0       34.06   0      
T529      III-8             2           0     0       0       0       0       37.74   0      
T530      III-8             2           0     0       0       0       0       36.73   0      
3B888     III-4     III-5   2           1/2   38.4    0       0       0       44.38   0      

I know how to do it for a single column

 awk '$3=="0"{$3=" "}; {print}' file

But how I do it for the three columns at the same time?

Thanks

1
  • thanks @JNevill, but this command awk '$2=="0" ; $3=="0" ; $5=="0" {$2=" ";$3=" ";$5=" "; print}' file does not produce the desired output, could you elaborate the answer please? Commented May 14, 2018 at 16:36

2 Answers 2

2

Following awk may help you on same.

awk '{$2=$2==0?"":$2;$3=$3==0?"":$3;$5=$5==0?"":$5;} 1' OFS="\t"  Input_file

Solution 2nd: Adding a more generic solution by which you could pass number of fields in function as follows.

awk '
function check_fields(a){
  num=split(a,array,",");
  for(i=1;i<=num;i++){
    $array[i]=$array[i]==0?"":$array[i]}
}
check_fields("2,3,5")
1
' OFS="\t"   Input_file
Sign up to request clarification or add additional context in comments.

Comments

0
awk '
    BEGIN { split("2 3 5", tmp); for (i in tmp) flds[tmp[i]] }
    { for (i in flds) if ($i == 0) $i = ""; print }
' file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.