Regex for accessing Linux files (numerical notation)

I can’t let my life determine the correct regular expression for this.

I am looking for a regular expression to match the actual numerical representation of permissions on Linux files (e.g. 740 for all-read-none, 777 for all-all-all). So far I have tried the following:

strtotest=740 echo "$strtotest" | grep -q "[(0|1|2|3|4|5|7){3}]" if [ $? -eq 0 ]; then echo "found it" fi 

The problem with the above is that the regular expression matches anything with 1-5 or 7 in it, regardless of any other characters. For example, if strtotest needed to be changed to 709 , the condition would be true. I also tried [0|1|2|3|4|5|7{3}] and [(0|1|2|3|4|5|7{3})] , but they do not work either.

Am I using regex or am I missing something related to grep ?

+7
source share
4 answers

The simplest and most obvious regular expression that will work for you is:

 grep -q '(0|1|2|3|4|5|7)(0|1|2|3|4|5|7)(0|1|2|3|4|5|7)' 

Here is the optimized version:

 grep -Eq '(0|1|2|3|4|5|7){3}' 

since 6 can also represent permissions, we could optimize it further:

 grep -Eq '[0-7]{3}' 
+5
source

what do you want probably

 grep -Eq "[0-7]{3}" 

edit: if you use this to search for files with specific permissions, you'd better take a look at find ( -perm ) or stat

+7
source
  • Your regular expression is very broken: [ ] defines a range, and all characters in it are in the allowed set.
  • grep has some additional citation rules that may require additional \ .
  • grep looks for your regular expression in each line - if you want to match only at the beginning of the line, you need ^ as the first char in the regular expression, and if you want to match the end you need $ at the end of the regular expression.
+3
source

Just for reference, you can do this with a shell template in Bash

 if [[ $strtotest == [0-7][0-7][0-7] ]]; then echo "Found it" fi 
+1
source

All Articles