Results 1 to 3 of 3
I am fairly new to linux but I want to write a function to find any file with only a partial name. I can only use sh shell and busybox ...
- 09-01-2010 #1Just Joined!
- Join Date
- Sep 2010
- Posts
- 5
[Question] How to find files with partial name
I am fairly new to linux but I want to write a function to find any file with only a partial name. I can only use sh shell and busybox applets for this.
I could do something like the sad code below...
I just made that up but obviously it is pretty badCode:TEST_ONE=$(find /path/to/directory -name *$1*) TEST_TWO=$(find /path/to/directory -name $1*) TEST_THREE=$(find /path/to/directory -name *$1) TEST_FOUR=$(find /path/to/directory -name $1) # incase the full name is given if [ ! -z $TEST_ONE ]; then YAY_I_FOUND_THE_FILE=$TEST_ONE elif [ ! -z $TEST_TWO ]; then YAY_I_FOUND_THE_FILE=$TEST_TWO elif [ ! -z $TEST_THREE ]; then YAY_I_FOUND_THE_FILE=$TEST_THREE elif [ ! -z $TEST_FOUR ]; then YAY_I_FOUND_THE_FILE=$TEST_FOUR else echo "coudln't find the file" fi
I'm sure there is a much better way to do it but I just can't think of a way. I also would like to have the file found even if capital letters are used and the file is all lower case.
- 09-01-2010 #2Just Joined!
- Join Date
- Sep 2010
- Posts
- 5
hmmm... got it down way better with
ls /path/to/directory | grep -i partial_file_name
If someone still knows a better way it would still be helpful
- 09-04-2010 #3
First of all, the "*foo*" pattern is called a shell glob. In a glob, the * means "0 or more characters", so you don't need four different patterns in your first script: just one of "*$1*" will do everything.
In any case, your first attempt was closer, I think. I would do it like this:
The "-iname" flag stands for "case-insensitive name". There is some bizarre quoting with the "*$1*" pattern because you want it to get passed to find, and not be executed by the shell.Code:find /path/to/dir -iname '*'"$1"'*'
Anyway, this will find a file that matches your pattern in the given directory OR ANY SUBDIRECTORY. If this is not want you want, you can add the "-maxdepth 1" flag, which will only look in the given directory.DISTRO=Arch
Registered Linux User #388732


Reply With Quote