Find the middle character from a string using sed

Input:

qwertmyuiop

It should print "m".
What's the command to do this with sed?

$ echo qwertmyuiop | sed ':a;s/.\(.*\)./\1/;ta'
m

or

sed -e ':a' -e 's/.\(.*\)./\1/;ta'
1 Like

Could you please explain these command?
(:a and ;ta) how are those use?

:a is a label ( label "a" )

ta means jump to label a is the previous command was successfull (if the s command managed to do a replacement)

So this creates a loop where after each iteration the outer two characters are removed until only the center character is left if there are an odd number of characters...

1 Like
echo "qwertmyuiop" |awk 'BEGIN{FS=OFS=""}{print $(NF/2+1)}'
1 Like
# x=$(expr $(echo qwertmyuiop | wc -c) / 2) ; sed "s/ */\n/$x" al | sed -n '2s/^\(.\).*/\1/p'
m
s="qwertmonyuiop"
echo ${s:((${#s}/2)):1}