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.

Suppose a directory contains the following files:

  • afile1
  • afile2
  • bfile
  • cfile
  • ffile
  • ffile2
  • qfile
  • zfile

I am looking for an easy way of selecting all the files which start with $LETTER, or start with a letter later than $LETTER in the alphabet. A solution that could be easily modified to find files that start with $LETTER or files which start with a letter earlier than $LETTER in the alphabet would be useful.

E.g. In the above list, with LETTER=c, I want to select "cfile, ffile, ffile2, qfile, zfile"

The above is a simplified example. In the real world the directory will contain several thousand files. In the end I used ls | tail -n${FUDGE_FACTOR}, where fudge factor was discovered manually, but am looking for a way to do this automatically.

I'm looking for a shell based solution to this (I use BASH, but solutions in other shells are welcome). I'm aware that shell scripts probably aren't the best tool for this task, but am asking purely out of interest (to learn more about shell scripts), so please don't reply with answers in python/perl/lua/$FAVE_SCRIPTING_LANGUAGE

General comments on the limitations of shell scripts for this kind of task, and the best way to work around these limitations in reality (i.e. without my "must be a shell based solution" stipulation), would be most welcome.

Thanks

share|improve this question

3 Answers 3

up vote 6 down vote accepted

It's actually very simple:

echo [$LETTER-z]*

If you want case-sensitivity:

echo [$(echo "$LETTER" | tr a-z A-Z)-Z$LETTER-z]*

This works because the shell performs parameter expansion before pathname expansion (i.e. globbing).

share|improve this answer

How about using the shell's built in globbing?

LETTER=c; echo [$LETTER-z]*

That worked in bash and ksh for me.

share|improve this answer

You could use a script like this:

START=c
END=q
ls | egrep ^[$START-$END].*

this would select all files that start with c through q.

sample output:

[gbeech@svr01 test]$ echo  ^[$START-$END].*
^[c-q].*
[gbeech@svr01 test]$ ls | egrep ^[$START-$END].*
cfile
ffile
ffile2
qfile

it could also be expanded to limit the grep, in just about any way you can adjust a regex to do.

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.