is there an 'upwards' find?

11

1

I found I asked this question on the wrong stackexchange site.

To find files starting from a certain path, I can use find <path> .... If I want to find 'upwards', i.e. in the parent directory, and it's parent, and..., is there an equivalent tool?

The use case is knowing the right number of dots (../../x.txt or ../../../x.txt?) to use in e.g. a makefile including some common makefile functions somewhere upstream.

Intended usage for a folder structure like this:

/
/abc
/abc/dce/efg/ghi
/abc/dce/efg2


$ cd /abc/dce/efg/ghi
$ touch ../../x.txt
$ upfind . -name X*
../../x.txt
$ upfind . -name Y* || echo "not found"
not found
$ touch /abc/dce/efg2/x.txt
$ upfind . -name Y* || echo "not found"
not found
$ 

So in short:

  • it should search on this folder, it's parent, it's parent's parent...
  • but not in any of their siblings (like 'find' would)
  • it should report the found file(s) relative to the current path

xtofl

Posted 2012-07-31T09:26:53.763

Reputation: 236

Possible same on unix SE: http://unix.stackexchange.com/questions/6463/find-searching-in-parent-directories-instead-of-subdirectories

– Ciro Santilli 新疆改造中心法轮功六四事件 – 2015-03-30T10:26:24.560

It appears from the link that you already wrote a script that solved your problem... – Matt – 2012-07-31T12:38:18.143

@Matt: yes, but I'm allways try to find one better answer, and this is a better forum to do so. – xtofl – 2012-07-31T12:50:42.100

Ah. Actually, I would think the best forum would be SO, wouldn't it? – Matt – 2012-07-31T12:52:45.523

Answers

17

You can use this simple script. It walks the directory tree upwards and seraches for the specified files.

#!/bin/bash
while [[ $PWD != / ]] ; do
    find "$PWD"/ -maxdepth 1 "$@"
    cd ..
done

Usage:

upfind -name 'x*'

choroba

Posted 2012-07-31T09:26:53.763

Reputation: 14 741

1

You can just split the path into its constituent directory nodes and search each one discreetly. It is a bash script.

IFS=/; dn=($1); ct=${#dn[@]}
for((i=0; i<ct; i++)); do
  subd+=/"${dn[i]}"
  dots=$(for((j=ct-i; j>1; j--)); do printf "../"; done)
  find "$subd" -maxdepth 1 -type f -name "$2" -printf "$dots%f\n"
done

run upfind $HOME/zt" "Y*" ... which produces the following output
when YABBA exists in /, /home/user, /home/user/zt

../../../YABBA
../YABBA
YABBA

Peter.O

Posted 2012-07-31T09:26:53.763

Reputation: 2 743