Skip to content

Instantly share code, notes, and snippets.

@ajithbh
Created June 7, 2014 09:16
Show Gist options
  • Save ajithbh/047f5a9b9be99d3d3bce to your computer and use it in GitHub Desktop.
Save ajithbh/047f5a9b9be99d3d3bce to your computer and use it in GitHub Desktop.
Bash string slice
string_slice()
{
[ -z $2 ] && echo "Usage: string_slice \"string\" start [end]" && return
string=$1
local len="${#string}"
local start="$2"
local end="$3"
:${end:=0}
if [ ${start} -lt 0 ]; then
start=$((${len} + ${start}))
fi
if [ ${end} -le 0 ]; then
end=$((${len} + ${end}))
fi
start=$((${start} + 1))
(echo "${string}" | cut -c ${start}-${end}) 2> /dev/null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment