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

3
  • Your question doesn't make any sense... do you mean that you want to get a list of arguments for the 'ls' command from a file?
    – MikeyB
    Jun 2, 2009 at 19:01
  • No, I want the output from the ls command to only include the filenames c3 to f
    – Noah
    Jun 2, 2009 at 19:14
  • Oh! You mean lexically... see my answer below. :p
    – MikeyB
    Jun 2, 2009 at 20:58

7 Answers 7

3

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

ls | awk '$1 >= "c3" && $1 <= "f" {print;}'
3

In bash, you can do something like:

$ ls [d-f]*

Or you could write a shell script.

2
  • This works great for single characters, which I know I put in the questions. Is there a general solution for longer prefixes?
    – Noah
    Jun 2, 2009 at 18:45
  • Anything more complex really requires learning to use grep, in my opinion.
    – Matt
    Jun 2, 2009 at 19:27
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.

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]
1

Along the lines of the previous answer:

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

ls [d-z]*
1
  • This works great for single characters, which I know I put in the questions. Is there a general solution for longer prefixes?
    – Noah
    Jun 2, 2009 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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .