[grep] finding a single Ampersand within a nested directory

I feel slightly stupid, but I need a bit of help. I have to find Ampersands (&) within a filetree (there are multiple nested folders with different depths) in actual text files.

For example there could be any character before or after the ampersand. I want to find ALL occurrences of it. Even those where they are in double (&&) or surrounded by whitespace.

I did try a lot of weird stuff with grep but nothing had me delivered sufficient results.

I know it’s probably some nice regex magic that’s needed, but I don’t get it.

Thanks in advance


If you install ripgrep, you can do:
rg \& or rg '&'

With grep, you may try: grep -rs -F '&'

1 Like

Do you want to find all file names that contain an &, or all files which contain &?

# Find all file names that contain an &
find -iregex '.*&+.*'

# Find all files that contain &. If you just want the name use `--files-with-matches`
grep --extended-regexp --recursive --regexp='.*&+.*'

Any character zero or more times
& one or more times
Any character zero or more times

Awesome site for regexs: http://www.regular-expressions.info/

grep --extended-regexp --recursive --regexp= '.*&+.*'

grep: .&+.: No such file or directory

@stargazer sadly I do get an error with this command. Do you know why?

grep -rs -F '&' 

contrary to the short grep above, which does result in an output. Thanks @cjean

Oooppss, remove the space after the = on --regexp.

hmm, somehow this still doesn’t give any results back compared to the 42 results of the other command.
only weird output, refering to pdf files and exe files

binary file matches

@cjean do you know a way to constrain this grep command to a certain assortment of file endings? (e.g. .c .h .cpp .hpp AND no fileending, the bare unix file)
Did it myself…just added
--include "*.cpp"

Thanks to everyone :slight_smile:

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.