#! /bin/bash # ############################################################################# NAME_="cpfile" PURPOSE_="find files of size n; copy to a specified dir; rename same file names" SYNOPSIS_="$NAME_ [-vhl] [-i ] -o -p \"\" -s <+|-n>" REQUIRES_="standard GNU commands" VERSION_="1.1" DATE_="2001-10-08; last update: 2004-12-30" AUTHOR_="Dawid Michalczyk " URL_="www.comp.eonworks.com" CATEGORY_="file" PLATFORM_="Linux" SHELL_="bash" DISTRIBUTE_="yes" # ############################################################################# # This program is distributed under the terms of the GNU General Public License usage () { echo >&2 "$NAME_ $VERSION_ - $PURPOSE_ Usage: $SYNOPSIS_ Requires: $REQUIRES_ Options: -i , path to where to look for files. Only needed if current dir is not used as input dir. -o , path to where to copy the found files. Each found file that has the same name as in the output dir will have an integer appended incrementally to the end of the prefix starting at 1. -s <+|-n>, file size in bytes; +n for greater then n; -n for less then n; n for exactly n. -p \"\", search file pattern as accepted by find's -name option; no case distinction is made. -v, verbose -h, usage and options (this help) -l, see this script" exit 2 } # args check [ $# -eq 0 ] && { echo >&2 missing argument, type $NAME_ -h for help; exit 2; } trap "exit 2" 1 2 3 15 # var init file_size= input_dir= output_dir= file_pattern= verbose= while getopts vhli:o:s:p: options; do case $options in s) file_size=$OPTARG ;; i) input_dir=$OPTARG ;; o) output_dir=$OPTARG ;; p) file_pattern=$OPTARG ;; v) verbose=on ;; h) usage ;; l) more $0; exit 2 ;; \?) echo invalid argument, type $NAME_ -h for help; exit 2 ;; esac done shift $(( $OPTIND - 1 )) # args check [[ $file_pattern ]] || { echo >&2 missing file pattern argument; exit 2; } [[ $file_size ]] || { echo >&2 missing file size argument; exit 2; } [[ -d $output_dir ]] || { echo >&2 output dir $output_dir does not exist; exit 2; } # local fnc c=0 rename_file() { # usage: fnc # keep on checking if file exist; if so, append integer to prefix if [ -f ${odir}/${1} ] ;then ((c++)) new_file_name=${1%%.*}${c}.${1#*.} rename_file $new_file_name # file does not exist else echo $1 c=0 fi } find_and_cp() { find . -type f -iname ${file_pattern} -size ${file_size}c | while read a; do file_name=$(rename_file ${a##*/}) [[ $verbose ]] && echo ${NAME_}: copying $a cp -- $a ${odir}/${file_name} done } # relative and full path support odir=$(cd $output_dir; pwd;) # main if [ $input_dir ];then # relative and full path support idir=$(cd $input_dir; pwd;) [ -d $idir ] || { echo input dir $idir does not exist; exit 2; } cd $idir find_and_cp else find_and_cp fi