[Techtalk] substring up to the first non-match character

Miriam English mim at miriam-english.org
Sun Feb 24 04:40:26 UTC 2013


I have two strings and I want to find the matching string plus the first 
non-matching character, starting from the first character.

I've written a simple bash loop that works its way forward through the 
strings ($str1 and $str2), dropping out when it encounters the first 
character that doesn't match.

	idx="0"
	while [ "${str1:$idx:1}" = "${str2:$idx:1}" ]
	do
	    ((idx += 1))
	done
	((idx += 1))
	str3="${str2:0:$idx}"

If $str1 is "abcdyz" and $str2 is "abcdmnopq" then $str3 is "abcdm"
If $str1 is "abc" and $str2 is "wxyz" then $str3 is "w"

It works well enough, however it bugs me that it's a bit clumsy and I'm 
haunted by the vague recollection that there is a single command that 
will do the job. Does anybody have any idea of what that command may be?

As explanation of its purpose, it is part of a little script I wrote 
that lets me use an empty placeholder file to mark my position in a 
sequence of audio files I'm listening to. I right-click the placeholder 
after I've listened to one of the files and choose "increment" (the name 
of my script) and it renames the placeholder so that it is repositioned 
in the file-listing after the file that I just finished listening to, 
and before the next one. So I can come back weeks or months later and I 
know where I'm up to. Cool, huh?

The files I've been listening to are the rather wonderful Short SF 
Collections available for free download from Librivox via the Internet 
Archive.

http://librivox.org
search for: science fiction collection

Cheers,

	- Miriam

-- 
If you don't have any failures then you're not trying hard enough.
  - Dr. Charles Elachi, director of NASA's Jet Propulsion Laboratory
-----
Website: http://miriam-english.org
Blogs:   http://miriam-e.dreamwidth.org
          http://miriam-e.livejournal.com



More information about the Techtalk mailing list