How to get the char at a given position of a string in shell script?
In bash with "Parameter Expansion" ${parameter:offset:length}
$ var=abcdef
$ echo ${var:0:1}
a
$ echo ${var:3:1}
d
Edit: Without parameter expansion (not very elegant, but that's what came to me first)
$ charpos() { pos=$1;shift; echo "$@"|sed 's/^.\{'$pos'\}\(.\).*$/\1/';}
$ charpos 8 what ever here
r
Alternative to parameter expansion is expr substr
substr STRING POS LENGTH
substring of STRING, POS counted from 1
For example:
$ expr substr hello 2 1
e
cut -c
If the variable does not contain newlines you can do:
myvar='abc'
printf '%s\n' "$myvar" | cut -c2
outputs:
b
awk substr
is another POSIX alternative that works even if the variable has newlines:
myvar="$(printf 'a\nb\n')" # note that the last newline is stripped by
# the command substitution
awk -- 'BEGIN {print substr (ARGV[1], 3, 1)}' "$myvar"
outputs:
b
printf '%s\n'
is to avoid problems with escape characters: https://stackoverflow.com/a/40423558/895245 e.g.:
myvar='\n'
printf '%s\n' "$myvar" | cut -c1
outputs \
as expected.
See also: https://stackoverflow.com/questions/1405611/extracting-first-two-characters-of-a-string-shell-scripting
Tested in Ubuntu 19.04.