Take the 2-minute tour ×
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.

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

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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

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
share|improve this answer
    
cool, should have checked expr more thoroughly. –  forcefsck Mar 17 '11 at 18:41
add comment

Your Answer

 
discard

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.