简体   繁体   中英

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.

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.

You don't need grep . Just use:

shopt -s nullglob
ls -d run*[0-9]

If your directories are not always ending with digits then use extglob :

shopt -s nullglob extglob
ls -d run*+([^.])

or to list all entries inside the run* directory ending without DOT:

printf "%s\n" run*+([^.])/*

This works...

ls|grep '.*[^.]$'

That is saying I want any amount of anything but I want the last character before the line ending to be anything except for a period.

我会用find

find -regextype posix-awk -maxdepth 1 -type d -regex '-*[[:digit:]]+$'

To list the directories that don't end with a . .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM