Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 2 down vote accepted
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|improve this answer
ls | grep $study | grep -o "[AX]$"

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

share|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
A
X

Or if you can use bash:

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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