Skip to content

Instantly share code, notes, and snippets.

@JaHIY
Last active November 26, 2021 00:33
Show Gist options
  • Save JaHIY/4d934b28c8284742057c to your computer and use it in GitHub Desktop.
Save JaHIY/4d934b28c8284742057c to your computer and use it in GitHub Desktop.
String-related functions in POSIX shell
#!/bin/sh -
substr() {
awk -v s="$1" -v i="$2" -v l="$3" 'BEGIN { print substr(s, i+1, l); }'
}
index() {
awk -v s="$1" -v c="$2" 'BEGIN { print index(s, c) - 1; }'
}
trim() {
tr -d '[:blank:]'
}
length() {
printf '%s' "$1" | wc -m | trim
}
ord() {
LC_CTYPE=C printf '%d' "'$1"
}
chr() {
[ "$1" -lt 256 ] || return 1
printf '%b' "$(printf '\%04o' "$1")"
}
repeat() {
printf '%*s' "$2" | sed -e "s/[[:blank:]]/$1/g"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment