1

This is my input file :

A B B A  
A A A   
B A B A  
B B  
A A  
A B

If all columns are same, I want to print only the first column.
Otherwise, I want to print multi.

Desired output :

multi  
A  
multi  
B  
A  
multi

Can anyone help me? (I prefer awk or sed.)

4

With AWK:

awk '{ for (i = 2; i <= NF; i++) { if ($i != $1) { print "multi"; next } }; print $1 }'

This processes each line as follows:

  • starting from the second field, compare each field to the first;
  • if a difference is found, print "multi" and move to the next line;
  • if no difference is found (the loop finishes, or is skipped entirely, e.g. for a line containing no or one field only), print the first field (and move to the next line).
|improve this answer|||||
2

awk/perl are the better tools for this job but you can do it with sed too:

sed -E 's/^([^[:blank:]]*)([[:blank:]]+\1)*$/\1/;t;s/.*/multi/' infile
|improve this answer|||||
0
$ awk '{b=$1; gsub($1,""); if (/^\s*$/) {print b} else {print "multi"}}' file         
multi
A
multi
B
A
multi
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.