简体   繁体   中英

find command can't exclude the exact regex

I have the following script:

#!/bin/bash
arg=$1
exclude='(/etc/alternatives/(awk|vim)|/usr/sbin/poweroff)$'
find $arg -type f,l,c,b -regextype posix-extended -not -regex "${exclude}" -print

I haven't used ^ at the beginning of each file so it could be started with anything. But I have used $ at the end of each file.

So when I run the script this way it is working properly:

$ sudo bash script.sh /etc/ | grep awk
/etc/alternatives/nawk
/etc/alternatives/nawk.1.gz
/etc/alternatives/awk.1.gz

But When I do that is faults:

$ sudo cp -rv /etc/ /tmp/
$ sudo bash script.sh /tmp/etc/ | grep awk
/tmp/etc/alternatives/awk
/tmp/etc/alternatives/nawk
/tmp/etc/alternatives/nawk.1.gz
/tmp/etc/alternatives/awk.1.gz

Here you see file /tmp/etc/alternatives/awk that shouldn't be passed at the result because of lacking ^ sign.

Update

This pattern is working nice but I want to use above one:

find $arg -type f,l,c,b | grep -Ev "${exclude}"

To the best of my knowledge, the -regex test is a feature specific to GNU's implementation of find ; it is not defined by POSIX. GNU's implementation is anyway almost certainly the one you will find on your favorite Linux distribution. Its manual has this to say:

Test: -regex expr
Test: -iregex expr
True if the entire file name matches regular expression expr. This is a match on the whole path, not a search . [...]

(emphasis added). That is, the test is always performed as if the regex were anchored to the beginning end end of the line, even if there are no explicit anchors in the pattern. You can work around that by prefixing and / or suffixing your regex with .* , as appropriate.

For your example, that might look like so:

exclude='.*(/etc/alternatives/(awk|vim)|/usr/sbin/poweroff)'

I have omitted the unneeded trailing anchor because that seems clearer to me, but if you prefer to retain it then do so -- it is not harmful.

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