Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How to get the char at a given position of a string in shell script?

share|improve this question
up vote 9 down vote accepted

In bash with "Parameter Expansion" ${parameter:offset:length}

$ var=abcdef
$ echo ${var:0:1}
$ echo ${var:3:1}

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
share|improve this answer
gnu.org/software/bash/manual/… has more details – jsbillings Mar 17 '11 at 15:24

Alternative to parameter expansion is expr substr

    substring of STRING, POS counted from 1

For example:

$ expr substr hello 2 1
share|improve this answer
cool, should have checked expr more thoroughly. – forcefsck Mar 17 '11 at 18:41

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.