Created
June 23, 2020 13:56
-
-
Save sathishvj/8fce0cee88be56a4e409f47c0d4f7d6c to your computer and use it in GitHub Desktop.
go into directory containing a file or dir matching a pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# go directly into a directory containing a file or directory with a matching pattern. | |
# use cdf to match a file, use cdd to match a dir | |
# e.g. | |
# cdd mydir # will match files of the type .*myfile.* | |
# cdd myd.subd # will match like .*myd.*subd.* | |
# cdd myd.subd$ # will match like .*myd.*subd$ | |
# cdf myfile # will match files of the type .*myfile.* | |
# cdf myfile.txt$ # will match files of the type .*myfile.txt$ | |
# go into dir with a specific file in the subdirectory. Uses regex and substitues . with .* | |
function cdf() { | |
local pat=$1 | |
#replace . with .* - so we can give multiple parts | |
pat=${pat//./.*} | |
if [[ $pat != ^* ]]; then #if it begins with a '^', leave it as is | |
pat=".*"$pat | |
else | |
local after=`echo $pat | cut -c 2-` | |
pat="^./"$after | |
fi | |
if [[ $pat != *$ ]]; then #if it ends with a '$', leave it as is | |
#pat=$pat".*" | |
# any character except another directory (/) | |
pat=$pat"[^/]*" | |
fi | |
#echo "pattern is $pat" | |
local f=$(find . -regex "$pat" -not -regex ".*git/.*" -not -regex ".*node_modules/.*" -not -regex ".*pkg/.*" -not -regex ".*google-cloud-sdk/.*" -not -regex ".*vendor/.*" -type f -print -quit 2>/dev/null | head -1) | |
if [ -z "$f" ]; then | |
echo #'not found' | |
return 1 | |
fi | |
echo "Found file: $f" | |
local d=$(dirname "$f") | |
cd "$d" | |
pwd | |
} | |
# go into a specific dir anywhere below this. Uses regex and substitues . with .* | |
function cdd() { | |
#replace in between "."s with .* | |
local pat=$1 | |
#replace . with .* - so we can give multiple parts | |
pat=${pat//./.*} | |
if [[ $pat != ^* ]]; then #if it begins with a '^', leave it as is | |
pat=".*"$pat | |
else | |
local after=`echo $pat | cut -c 2-` | |
pat="^./"$after | |
fi | |
if [[ $pat != *$ ]]; then #if it ends with a '$', leave it as is | |
pat=$pat".*" | |
fi | |
#echo "pattern is $pat" | |
local d=$(find . -regex "$pat" -not -regex ".*git/.*" -not -regex ".*node_modules/.*" -not -regex ".*pkg/.*" -not -regex ".*google-cloud-sdk/.*" -not -regex ".*vendor/.*" -type d -print -quit 2>/dev/null | head -1) | |
if [ -z "$d" ]; then | |
echo #'not found' | |
return 0 | |
fi | |
#echo "going to $d" | |
cd "$d" | |
pwd | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment