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 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...