I have a string that is always 3 characters... the first one and the last one are always the same.
example:
▁▅█
Is there a simple way to only display the one in the middle? (which is the only one that changes)
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityYes, 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
\K
restart the match to zero (see pcre
doc)$(cat)
in python is a shell hack to get STDIN
For variety, here's one way with dd
:
echo ixi | dd bs=1 skip=1 count=1 2>/dev/null
If your grep doesn't support perl (-P
), you could do it like this:
echo ixi | grep -o . | sed -n 2p
These alternatives only work for one-line input.
you can also do this way, by using the looking around technique, so the second char "x" following the examples above using "ixi",
echo ixi | grep -oP "(?<=^.)."