How to remove odd indexed characters from a given string in Linux

Let’s suppose I have the string ‘1H2e3l4l5o’ and I want to keep ‘Hello’

Is there a way to do it with sed command? I’m just getting started

echo "1H2e3l4l5o" | sed 's/{answer goes here?}//'

Hello

>Solution :

One sed idea:

$ echo "1H2e3l4l5o" | sed -En 's/.(.)/\1/gp'
Hello

Where:

  • -En – enable support for extended regex operations and disable the default printing of the pattern space
  • .(.) – match 2 characters, save the 2nd character in the 1st (and only) capture group; replace the 2 characters with …
  • \1 – the contents of the (1st) capture group
  • gp – repeatedly apply the change to the rest of the input until you get to the end of the line, printing the changes to stdout

Leave a Reply