Back to index

Searching files and content with find and xargs

Published by bolmaster2

Showing all files with the word “My lost word” in them. Prepended with the filenames.

Usually I use grep only with standard input but in this case we would lose the file path if we did that. So xargs to the rescue! It takes the output of the previous command and add it to the last argument to the next. Beautiful and simple magic! 🔮

find / -name *.txt | xargs grep -H "My lost word"

Regular expression! Just wanted to get that in here because it can be useful to filter the searched files.

find . -regex '.*/[a-z].txt' | xargs grep -H "My lost word"

Remember to use .*/ to match the whole path.

find . -regex '.*/[0-9].jpg'

One thing to remember is that find, at least on my macOS High Sierra can’t handle the + operator which really is a shame. So for example this won’t work:

find . -regex '.*/[0-9]+.jpg'

The above should match all files like 1.jpg, 30.jpg or 9999999.jpg for that matter. The + should make the preceding expression match one or more times. It works everywhere! But not on mac 💩. There is no--version or -v or anything to see which version it is. It obviously comes from some BSD version (man find says BSD General Commands Manual). But which is a mystery for me.

Get rid of annoying error output

When you’re not root and search the whole filesystem you will for sure get a lot of permission denied output which can be overwhelming. There’s a trick to get rid of that:

find / -regex '.*/[0-9]+.jpg' 2>/dev/null

As 2 is Standard error, i.e., stderr it will redirect all errors to /dev/null which is a black hole where you never ever come back from if you get in 😱.