2016年2月18日 星期四

[Linux 常見問題] Shell - Find folder where contains specific file name

Question
Sometimes, you many want to list the folder(s) where contain specific file name. This time, you can leverage command find with argument '-name'

Sample code
Below sample code will look for all folders under specific path which contains '.jazz?' file (? can be any character):
  1. findBuildDirs()  
  2. {  
  3.     find $1 -maxdepth 2 -mindepth 2 -name '.jazz?' -type d | sed 's!/\.jazz[0-9]$!/!' | xargs -r ls -dt1  
  4. }  

Usage Example
First of all, let's check what we have under folder var using command tree:
 


And we want to find the folder which contains '.jazz?'. Let's use command find this way:
# find var -name '.jazz?'
var/C1/tmp/.jazz5
var/C3/.jazz5
var/C4/.jazz3

However, I only want '.jazz?' to exist under the exact depth=2 from var folder. Then we can do it this way:
# find var -maxdepth 2 -mindepth 2 -name '.jazz?'
var/C3/.jazz5
var/C4/.jazz3

Now the output is close to our expectation. Next step is to use command sed to remove out the '.jazz?':
# find var -maxdepth 2 -mindepth 2 -name '.jazz?' | sed 's!/\.jazz[0-9]$!/!'
var/C3/
var/C4/

Finally, you many want to list the folder with order in modification time, try this:
// sort by modification time, newest first
# find var -maxdepth 2 -mindepth 2 -name '.jazz?' | sed 's!/\.jazz[0-9]$!/!' | xargs -r ls -td1
var/C4/
var/C3/


沒有留言:

張貼留言

[Git 文章收集] Differences between git merge and git rebase

Source From  Here Preface Merging and rebasing are the two most popular way to applying changes from one branch into another one. They bot...