Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    [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...

    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
    elif [ ! -z $TEST_TWO ]; then
    elif [ ! -z $TEST_THREE ]; then
    elif [ ! -z $TEST_FOUR ]; then
       echo "coudln't find the file"
    I just made that up but obviously it is pretty bad 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.

  2. #2
    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

  3. #3
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Seattle, WA, USA
    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:
    find /path/to/dir -iname '*'"$1"'*'
    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.

    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.

  4. $spacer_open

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts