Thursday, November 22, 2007

Linux: Using the 'find' command.

In Linux, often times you'll need to find files using patterns like '*.txt' or 'sys*.*' and do operations with the results. You can do that in several ways. A harder way will be writing a complicated script using the 'ls' and 'grep' commands in pipe. But the 'find' command is one of the easier ways. I'm using the terms 'easier' as I'm not sure of the 'easiest' way as I am not a Linux guru.. well yet.. ;)

The 'find' command is powerfull but if you're a begginer, you'll hardly understand the help or manual of it. I won't re-write the man page in some easy way here, rather I'll just give some examples so that you can quickly use it and understand the man page later on. So, here goes the examples:

1. Search all '.txt' files in the current directory, including its subdirectories:

find . -iname "*.txt"

2. Search all files with the name 'pre_*.txt' (example: pre_01.txt, pre_abcd.txt, etc) in the 'src/dir', including its subdirectories:

find src/dir -iname "pre_*.txt"

3. Search all '.txt' files in the current directory, including its subdirectories, and copy/move them to another directory:

find . -iname "*.txt" -exec cp {} /dest/dir \;
find . -iname "*.txt" -exec mv {} /dest/dir \;

Note: don't forget the '\;' in the end, it won't work otherwise.

4. Find all .htm files in the current directory, including its subdirectories, and compress them into a gzip file naming 'output.tar.gz', maintaining the directory structure that they were found in:

find . -iname "*.htm" > temp.txt
tar -czT temp.txt -f output.tar.gz

I hope this post will be helpful to you sometime.

1 comment:

Unknown said...

I find myself looking for c/c++ files by doing this:

find . -iname '*.[h|c]' -o -iname '*.[h|c]pp'

I'm trying to find a way to combine the two -inames, but I'm still learning regular expressions.