Using grep to display second character in string?
Yes, try doing this, and pick your preferred method =) :
With grep:
echo "ixi" | grep -oP "^.\K."
With cut:
echo "ixi" | cut -c2
With bash parameter expansion :
x='ixi'; echo ${x:1:1}
With sed:
echo "ixi" | sed 's/.\(.\)./\1/'
or
echo "ixi" | sed 's/\(^.\|.$\)//g'
With perl:
echo "ixi" | perl -lne 'print $& if /^.\K./'
With ruby:
echo "ixi" | ruby -ne 'print $_.split(//)[1]'
With awk:
echo 'ixi' | awk '{split($0, a, ""); print a[2]}'
With python:
echo "ixi" | python -c 'print list("'$(cat)'")[1]'
or
python -c 'import sys; print list(sys.argv[1])[1]' ixi
NOTE
\K
restart the match to zero (seepcre
doc)$(cat)
in python is a shell hack to getSTDIN
You could also use sed
instead of grep
:
sed 's/.\(.\)./\1/'
This says:
s/
... match the expression up to the next/
character..
... match the first character (any).\(.\)
... match the next character and remember it..
... match the third character (any)./
... denotes the end of the expression.\1
... replace the entire string that matched with the character that was remembered./
... end of replacement text.
Thus:
$ echo "abc" | sed 's/.\(.\)./\1/'
Will print:
b