Extract part of string using grep

12,175
ls | grep -oP "(?<=$study.)[A-Z]$"

will return any uppercase letter that is preceded by the contents of $study plus one arbitrary character (the T in your example) and followed by the end of the line.

The -P option (Perl regular expressions) is needed to be able to use the positive lookbehind expression (?<=...), but might not be available on every system and platform.

Share:
12,175

Related videos on Youtube

moadeep
Author by

moadeep

Updated on September 18, 2022

Comments

  • moadeep
    moadeep over 1 year

    I have 3 files in a directory

    MYO144064T
    MYO144064TA
    MYO144064TX
    

    Where the digits and 11th character will change. In my csh script, I want to extract the letters 'A' and 'X' probably using grep

    The variable $study equals MYO144064

    What I have managed so far is very cumbersome

    ls | grep $study | cut -c 11 | sed 's/\///'
    

    Which gives me

    A
    X
    

    How can I do this with minimal processes and without the additional blank line?

  • moadeep
    moadeep about 10 years
    The 11th character will change, it may be A or X but could easily be M, Y, O or T
  • rob
    rob about 10 years
    then ".$" will always get you the last character