* [gentoo-dev] pure bash implementations of 'index' and 'rindex'
@ 2003-08-12 7:58 Robin H. Johnson
0 siblings, 0 replies; only message in thread
From: Robin H. Johnson @ 2003-08-12 7:58 UTC (permalink / raw
To: luke-jr; +Cc: gentoo-dev
[-- Attachment #1.1: Type: text/plain, Size: 325 bytes --]
Luke-Jr asked in #gentoo-dev for these, but I thought others might find
them useful as well.
--
Robin Hugh Johnson
E-Mail : robbat2@orbis-terrarum.net
Home Page : http://www.orbis-terrarum.net/?l=people.robbat2
ICQ# : 30269588 or 41961639
GnuPG FP : 11AC BA4F 4778 E3F6 E4ED F38E B27B 944E 3488 4E85
[-- Attachment #1.2: index.bash --]
[-- Type: text/plain, Size: 1819 bytes --]
#!/bin/bash
# Minimalist implementations of the 'index' and 'rindex' functions in pure Bash
# returns a 0 based offset into your haystack string
# This is provided solely as-is, and all I ask is a one line thank you note
# with my email address.
# Written by Robin H. Johnson <robbat2@orbis-terrarum.net>
function index() {
local haystack="$1"
local needle="$2"
local fromstart="${3-0}"
haystack="${haystack:${fromstart}}"
local tmp="${haystack/${needle}*}"
[ "${#tmp}" -ge "${#haystack}" ] && echo -1 || echo $((${#tmp}+${fromstart}-1))
}
function rindex() {
local haystack="$1"
local needle="$2"
local fromend="${3-0}"
haystack="${haystack:0:$((${#haystack}-${fromend}+1))}"
local tmp="${haystack%${needle}*}"
[ "${#tmp}" -ge "${#haystack}" ] && echo -1 || echo $((${#tmp}-1))
}
# Testing code
HAYSTACK="Mary had a little lamb but the lamb had had measles"
NEEDLE="had"
echo "'${HAYSTACK}' (${#HAYSTACK})"
echo -n "Looking for needle '${NEEDLE}' [expect 4]: "
index "${HAYSTACK}" "${NEEDLE}"
echo -n "Looking for needle '${NEEDLE}' after 7 [expect 35]: "
index "${HAYSTACK}" "${NEEDLE}" 7
echo -n "Looking for needle 'foo' [expect -1]: "
index "${HAYSTACK}" "foo"
echo -n "Looking for needle 'foo' after 7 [expect -1]: "
index "${HAYSTACK}" "foo" 7
echo -n "Looking for needle '${NEEDLE}' in reverse [expect 39]: "
rindex "${HAYSTACK}" "${NEEDLE}"
echo -n "Looking for needle '${NEEDLE}' in reverse skipping 10 [expect 35]: "
rindex "${HAYSTACK}" "${NEEDLE}" 10
echo -n "Looking for needle '${NEEDLE}' in reverse skipping 20 [expect 4]: "
rindex "${HAYSTACK}" "${NEEDLE}" 20
echo -n "Looking for needle 'foo' in reverse [expect -1]: "
rindex "${HAYSTACK}" "foo"
echo -n "Looking for needle 'foo' in reverse skipping 10 [expect -1]: "
rindex "${HAYSTACK}" "foo" 10
[-- Attachment #2: Type: application/pgp-signature, Size: 232 bytes --]
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2003-08-12 7:58 UTC | newest]
Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2003-08-12 7:58 [gentoo-dev] pure bash implementations of 'index' and 'rindex' Robin H. Johnson
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox