0

I'm using this code to find all php files in a bash script.

for f in $(find ./src -name '*.php'); 
do 
    echo "$f"; 
done

How can i go through all *.php files but ignore ones that start with _ ?

For example it should list index.php, but not _menu.php

Thanks in advance

  • Did you try `... -name "[^_]*.php"` – lurker Jul 01 '19 at 10:57
  • Possible duplicate of [How do I find all files that do not begin with a given prefix in bash?](https://stackoverflow.com/q/21368838/608639), [List all files not starting with a number](https://stackoverflow.com/q/9515263/608639), [find filenames NOT ending in specific extensions on Unix?](https://stackoverflow.com/q/1341467/608639), etc. – jww Jul 01 '19 at 11:08
  • Do you mean the first letter of the filename, or the first character in the content? – kvantour Jul 01 '19 at 11:54
  • `find /path -type f -name "*php" ! -name "_*"` – David C. Rankin Jul 01 '19 at 17:43
  • @kvantour see the example „but not _menu.php“ – eckes Jul 01 '19 at 17:45

2 Answers2

2

You can try the following:

#!/bin/bash
find ./src -name '[^_]*.php' | \
while read -r filename; do
   echo "$filename"
done   

explanation

[^_]*     # all characters without _ at start 
UtLox
  • 3,744
  • 2
  • 10
  • 13
  • Actually `[^_]*` means zero or more characters but none of them are `_`, and you cannot use RE with -name. – eckes Jul 01 '19 at 17:38
2

The -name parameter does allow fnmatch style globing patterns, which is not a regular expression and has no negative patterns. So you need one of two alternatives (if you want to filter inside the find operation):

You have the option to use a RE instead. You need to be aware that regular expressions match against the whole path not the name only, so something like this should work:

find ./src -regex '.*/[^_/][^/]*\.php'

An alternative is to combine -name with a negation expression (-a -not means „and not“):

find ./src -name '*.php' -a -not -name '_*'
eckes
  • 10,103
  • 1
  • 59
  • 71