Pages

Thursday, December 28, 2017

Usage of Unix/Linux find command with exec cp along with sed, xargs and tr

The Linux find is a popular command for search, and using the -exec parameter we can apply other commands on every result.

Here I am specifying the use of cp along with the find -exec recursively, i.e. maintaining the parent directory

Other commands are used/demonstrated:  sed, xargs, echo and tr

At the end I shall mention some work arounds to make the GnuWin32 find functional in Windows. (I used in windows 10, I like the power of unix commands )




 
#Command to get files list modified in last 48 hours except txt and log files:
 find . -type f -mtime -2 # -type f lists only files
#Example: sed used to remove preceding ./ and to exclude *.txt and *.log files  
 find . -type f -mtime -2 | sed "s/.\// /" | sed -r "/(txt|log)/d"
#Example: excluding *.txt and *.log using find's name parameter the caret (^) does the job
 find . -type f  -name "*[^txt|log]"  -mtime -2
 
 #Command to get file list modified in last 10 minutes:
 find . -type f -mmin -10
 
 #Command to copy latest files wiht preserving directory structures/parents
 find . -type f -mtime -2 | sed -r "/(txt|log)/d" |  xargs cp --parents -t d:\code
 find . -type f  -name "*[^txt|log]"  -mtime -2 |  xargs cp --parents -t d:\code
 find . -type f  -name "*[^txt|log]"  -mtime -2  -exec cp --parents  {}  -t d:\code \; #for linux or cigwin/ gitbash
 
 find . -type f  -name "*[^txt|log]"  -mtime -2  -exec cp --parents  {}  -t d:\code \ ;#for Windows using GnuWin32 " " a single white spaec
 
 #Examples: Command to make file names in a single line space separated
 find . -type f -mtime -2 | sed "s/.\// /" | sed -r "/(txt|log)/d" | tr -d "\r\n"
 find . -type f -name "*[^txt|log]"  -mtime -2 | sed "s/.\// /"  | tr -d "\r\n"
 find . -type f -name "*[^txt|log]"  -mtime -2 | sed "s/.\///"  | xargs echo # echo automatically separates name by space
 
 #Copy with maintaining the parent directory structures
cp --parents 


For Windows, the GnuWin32 find is renamed findg since the Windows' native find get precedence if the GnuWin32 path is appended at last.

Secondly, if -exec is used we need to put a white space between \ and ;

No comments :

Post a Comment