I have a problem to compare a long list of names.

RamaKrishna  KrishnaRama 
IndiaUS      USIndia

shall be compared and they are to be declared as equal.

I wanted to solve this by rearranging all characters in each word alphabetically like this

adiiNSU adiiNSU

then comparing each word. How can I do this using bash script.

  • show how should look the expected output – RomanPerekhrest Nov 23 '17 at 8:03
  • are the words always in pair in each line which are to be compared? what did you try to solve this yourself? – Sundeep Nov 23 '17 at 8:33

Extended GNU AWK solution:

Sample inputfile contents:

RamaKrishna  KrishnaRama 
IndiaUS      USIndia
UkraineMotherland RepublicUkraine

awk 'BEGIN{ PROCINFO["sorted_in"]="@str_val_asc" }
         len=split($1,w1,""); split($2,w2,""); asort(w1); asort(w2); not_eq=0; 
         for (i=1; i<=len; i++) if (w2[i]=="" || w1[i] != w2[i]) { not_eq=1; break } 
         print $0,"-",(not_eq? "not equal":"equal") 
     }' inputfile

The output:

RamaKrishna  KrishnaRama  - equal
IndiaUS      USIndia - equal
UkraineMotherland RepublicUkraine - not equal

I'd use perl here:

perl -Mopen=locale -lane '
  sub rearrange {
    return join "", sort split("", $_[0])
  print if rearrange($F[0]) eq rearrange($F[1])' < file

Would print those lines of file where the first field is the same as the second after that rearranging.

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.