bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: finding the index at which two strings differ


From: Mike Stroyan
Subject: Re: finding the index at which two strings differ
Date: Tue, 6 May 2008 16:18:35 -0600
User-agent: Mutt/1.5.17+20080114 (2008-01-14)

On Tue, May 06, 2008 at 01:29:13PM -0600, Bob Proulx wrote:
> Poor Yorick wrote:
> > Looking for a simple ways to output the index at which two strings
> > differ.  Here is one:
> > 
> > cmp <(echo "hello") <(echo "help") | cut -d' ' -f5 | tr -d ,
> > 
> > Any other suggestions?

You could use substring expansion to compare characters one by one.

#!/bin/bash
a=$1
b=$2
if [[ "$a" == "$b" ]]
then
  echo "'$a' and '$b' are the same"
else
  i=0
  while [[ "${a:$i:1}" == "${b:$i:1}" ]]
  do
    let i++
  done
  let i++
  echo "'$a' and '$b' differ in character $i"
fi

-- 
Mike Stroyan <mike@stroyan.net>




reply via email to

[Prev in Thread] Current Thread [Next in Thread]