3

The main problem is my directory has many files with uppercase (e.g. Foobar.txt, FooBar.txt, even FOOBAR.txt). And I find it messy to find the files by exactly typing it (if I know the exact filenames, why would I use find?). So I want to type just foobar and want all three files in result

Also, I am using * both of the side of my string to match any number of characters preceding and appending in the file name.

I want an alias or function that does this.

1
  • I don't see the advantage of an function here.
    – Bernhard
    Commented Aug 27, 2012 at 5:54

2 Answers 2

13

The correct way then would be

find -iname \*foobar\*

Where -iname is for case insensitive search, and the \ to escape the * wildcard.

The function seems a bit unnecessary for this case, but it is easy to write

function lazyfind ()
{
    find -iname \*$1\*
}
6
  • Hey! its hard to type the escape characters everytime, do anything.. Commented Aug 27, 2012 at 6:05
  • Well, for these simple tasks, I think it is better to type them again. Especially when working on multiple machines, it also annoying to copy functions for simple tasks.
    – Bernhard
    Commented Aug 27, 2012 at 6:15
  • @santosh, you can get the same result by using quotes: find -iname "*foo*".
    – terdon
    Commented Aug 27, 2012 at 11:10
  • 1
    And using quote is more friendly if $1 can contain spaces.
    – ams
    Commented Aug 28, 2012 at 12:03
  • And how to do that recursively? Commented Jan 22, 2013 at 8:26
0

Should you OS is missing GNU find -iname option, here is a portable way to achieve the same:

cifind()
{
  pattern=""
  l=${#1}
  i=1
  while [ $i -le $l ] ; do
    lc=$(echo "$1" | cut -c $i-$i | tr '[A-Z]' '[a-z]')
    uc=$(echo "$lc" | tr '[a-z]' '[A-Z]')
    if [ ."$lc" != ."$uc" ] ; then
      pattern="${pattern}[$lc$uc]"
    else
      pattern="${pattern}$lc"
    fi
    i=$((i + 1))
  done
  find . -name "*$pattern*"
}
3
  • 1
    Make that l=$(expr "x$1" : '.*') and [ $i -le $l ], in case $1 begins with -. Or embrace POSIX and write l=${#1}, the script will be faster. Or use awk, which will be easier, less error-prone and faster. Commented Aug 27, 2012 at 23:36
  • @Gilles: For some reason, I thought ${#var} wasn't posix, thanks for the head-up. I don't think there is an issue with [ $i -le $l ] , however, I also corrected $lc != $uc to .$lc != .$uc to properly handle hyphens.
    – jlliagre
    Commented Aug 28, 2012 at 0:30
  • Arithmetic expressions ($((…))) are POSIX too. I meant [ $i -lt $l ] in my first comment, because "x$1" is one character longer — but using ${#1} is clearer. Commented Aug 28, 2012 at 12:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .