Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading