1

For example, if my directory contains files a, b, c, c1, c2, c3, c4, d, e, f, g

Is there a command something like the following pseudo code

ls -filename>"c2"

that would only list files c3, c4, d, e, f

EDIT: Modified question to address a more general case

Noah
  • 259
  • 6
  • 12

7 Answers7

3

In bash, you can do something like:

$ ls [d-f]*

Or you could write a shell script.

Matt
  • 436
  • 3
  • 8
  • This works great for single characters, which I know I put in the questions. Is there a general solution for longer prefixes? – Noah Jun 02 '09 at 18:45
  • Anything more complex really requires learning to use grep, in my opinion. – Matt Jun 02 '09 at 19:27
3

Ah - you mean you want to search within a lexical ordering. Use this:

ls | awk '$1 >= "c3" && $1 <= "f" {print;}'
MikeyB
  • 39,291
  • 10
  • 105
  • 189
2

Using regular expressions:

ls | egrep "[d-z].*"

This is usually the case for odd requests like yours. You're asking ls to do something that is very unusual and involves understanding the lexical structure of the directory names.

Go learn regular expressions at: regular-expressions.info

And type:

man grep

To read the manual page for grep.

Neil
  • 2,425
  • 8
  • 36
  • 45
1

Using the grep command, you can do any type of filtering needed. Similiar to the FIND command in Windows. Below is one option. If you want to get a full listing, like what you get with "ls -l" then you may have to combine that with AWK.

> ls -1 | grep ^[def]
KodeTitan
  • 881
  • 2
  • 10
  • 15
1

Along the lines of the previous answer:

use the shell's filename expansion instead of using egrep:

ls [d-z]*
TCampbell
  • 2,024
  • 14
  • 14
  • This works great for single characters, which I know I put in the questions. Is there a general solution for longer prefixes? – Noah Jun 02 '09 at 18:43
0

ls | grep -A 1000000 '^c2$' | tail -n +2

The grep gives you the line that matches and the next million; the tail chops off the first line.

If you want a long version, adding "| xargs ls -l" to the end would work.

Limitations: this won't work well with funky filenames (especially filenames with newlines, but might have trouble with spaces, control characters, etc.). And it won't work if you have over a million files in the directory.

freiheit
  • 14,544
  • 1
  • 47
  • 69
0

Is not the definitive answer, but this should work.

ls -1 | while read f ; do [[ "$f" > "g2" ]] && echo $f ; done

It could be more evolved using "$(echo $f | tr [A-Z] [a-z])" so it will ignore case. This works only for ASCII strings, it won't be able to order Unicode (or iso-*) filenames

Pablo Martinez
  • 2,406
  • 17
  • 13