Find the answer to your Linux question:
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 ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just 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...

    Code:
    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 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
    Just 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

  3. #3
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,252
    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:
    Code:
    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
    $spacer_close

Posting Permissions

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