Search code examples
regexlinuxls

ls and regular expression linux


I have two directories:

  1. run.2016-02-25_01.
  2. run.2016-02-25_01.47.04

Both these directories are present under a common directory called gte.

I want a directory that ends without a dot character ..

I am using the following command, however, I am not able to make it work:

ls run* | grep '.*\d+' 

The commands is not able to find anything.


Solution

  • The negated character set in shell globbing uses ! not ^:

    ls -d run*[!.]
    

    (The ^ was at one time an archaic synonym for |.) The -d option lists directory names, not the contents of those directories.


    Your attempt using:

    ls run* | grep '.*\d+'
    

    requires a PCRE-enabled grep and the PCRE regex option (-P), and you are looking for zero or more of any character followed by one or more digits, which isn't what you said you wanted. You could use:

    ls -d run* | grep '[^.]$'
    

    which doesn't require the PCRE regexes, but simply having the shell glob the right names is probably best.

    If you're worried that there might not be a name starting run and ending with something other than a dot, you should consider shopt -s nullglob, as mentioned in Anubhava's answer. However, note the discussion below between hek2mgl and myself about the potentially confusing behaviour of, in particular, the ls command in conjunction with shopt -s nullglob. If you were using:

    for name in run*[!.]
    do
        …
    done
    

    then shopt -s nullglob is perfect; the loop iterates zero times when there's no match for the glob expression. It isn't so good when the glob expression is an argument to commands such as ls that provide a default behaviour in the absence of command line arguments.