Created
June 7, 2014 09:16
-
-
Save ajithbh/047f5a9b9be99d3d3bce to your computer and use it in GitHub Desktop.
Bash string slice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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