I have 3 files in a directory


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


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

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.

| improve this answer | |
ls | grep $study | grep -o "[AX]$"

returns only the result of 'A' or 'X' as the last character

| improve this answer | |
  • The 11th character will change, it may be A or X but could easily be M, Y, O or T – moadeep Mar 27 '14 at 13:32
  • then ".$" will always get you the last character – rob Mar 27 '14 at 13:48

A perl solution:

$ perl -nle 'print chop if length == 11' file

Or if you can use bash:

while read var
    [ ${#var} -eq 11 ] && echo ${var:(-1)}
done < file
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.