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.)

3 Answers 3

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).
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
0
$ awk '{b=$1; gsub($1,""); if (/^\s*$/) {print b} else {print "multi"}}' file         
multi
A
multi
B
A
multi

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.