6

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)

4 Answers 4

14

Yes, try doing this, and pick your preferred method =) :

With :

echo "ixi" | grep -oP "^.\K."

With :

echo "ixi" | cut -c2

With parameter expansion :

x='ixi'; echo ${x:1:1}

With :

echo "ixi" | sed 's/.\(.\)./\1/'

or

echo "ixi" | sed 's/\(^.\|.$\)//g'

With :

echo "ixi" | perl -lne 'print $& if /^.\K./'

With :

echo "ixi" | ruby -ne 'print $_.split(//)[1]'

With :

echo 'ixi' | awk '{split($0, a, ""); print a[2]}'

With :

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 (see pcre doc)
  • $(cat) in python is a shell hack to get STDIN
3
  • 3
    +1 for the nice use of grep. Nov 15, 2012 at 17:11
  • 3
    Added the sortest one : cut Nov 15, 2012 at 17:36
  • loved that grep
    – Mr.Gando
    Nov 16, 2012 at 4:35
1

        ︙
or

echo "ixi" | awk '{print substr($0,2,1)}'

or

expr "ixi" : '.\(.\).'
1

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.

0

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 "(?<=^.)."

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .