Thursday, June 12, 2008

Tricks for massive file manipulation

(modified 2010-01-26)

# List all .pyc files (or directories) in current directory and below:
find . -name '*.pyc'

# Remove all .pyc files (or directories) from current directory and below:
find . -name '*.pyc' -exec mv {} ~/.trash \;

# Remove all files from build directory and below, and also remove them from cvs:
find . -type f -wholename './build/*' -exec rm {} \; -exec cvs remove {} \;

# Find all .py.metadata files (or directories) in or below /path/to/directory, print the lines containing 'proxy', also list the filename (-H)
find /path/to/directory -name '*.py.metadata' -exec grep -H proxy {} \;

# Find all files or directories in current directory and print only their names:
find . -regex './[^/]*' -printf "%p"

# Find all files older than 30 days (by modification date) and print the modification date and name:
find . -type f -mtime +30 -printf '%t\t%p\n'

# Find directories in current folder not modified in the last 30 days, print modification date and name, and delete:
find . -regex './[^/]*' -type d -mtime +30 -printf '%t\t%p\n' -delete

# Find
# - files and directories in current folder:
# - not accessed in last month (if it's a folder)
# and do this:
# - delete it
# - (and possible subfolders)
find . -maxdepth 1 -name "*" -atime +31 -print0 | xargs -0 rm -rf

# Replace all occurrences of 'foo' by 'bar' in all files below this level
find . -name "*" -type f | xargs perl -pi -e 's/foo/bar/g'

# Rename files: replace 'foo' in filename with 'bar'.
# This may give errors if 'foo' occurs in more than one place on the path,
# but you can simply run it more than once.
find . -name "*foo*" | xargs rename 's/(.*)foo(.*)/$1bar$2/'

No comments: