如何构建自定义grep函数

时间:2013-03-27 18:24:59

标签: bash shell

我是bash的新手,我正在尝试构建自己的grep别名来搜索文件 这是我建立的脚本:

function gia() {
  if [ -z "$1" ]; then
    echo "-You need to define what are you looking for-"
  else
    echo "-Looking for \"$1\".-"
    if [ -z $2 ]; then
      echo "-no path passed, searching all files-"
      grep -i --color "$1" ./*
    else
      echo "-Looking in \"$2\".-"
      grep -i --color "$1" $2
    fi
  fi
}

第二个选项效果不好,如果我尝试一下,我会得到这个输出:

$$ gia 'sometext' ./*.html
-Looking for "sometext".-
-Looking in "./login.html".-

我从未指定 login.html ,但它占用了我目录中的一个文件并在其中进行了搜索。并且grep失败了。

例如,如果我在 myfiles 目录中有3个文件:

1.html 2.txt 3.html

和3.html的文字为“反引号”

如果我这样搜索:

cd myfiles
gia 'backquotes'

我得到了结果

-Looking for "backquotes".-
-no path passed, searching all files-
./3.html:    <backquotes>...</backquotes>

但是如果我是root用户,那就搜索一下:

gia 'backquotes' ~/myfiles/*.html

我明白了:

-Looking for "backquotes".-
-Looking in "./1.html".-

没有结果回来,因为它只在1.html搜索。如果我在1.html中有“反引号”。它会回来,但我从其他文件中得不到任何东西,它只在第一个文件中搜索并退出。

我知道明星是bash中的特殊角色,但我该如何解决?

提前感谢您的帮助。

EMMNS

2 个答案:

答案 0 :(得分:2)

如果要对函数使用'wildcard'文件名,则必须解析$ @。这是函数的参数列表。我暂时离开了这个解决方案的解析路径。

function gia() {
  if [ -z "$1" ]; then
    echo "-You need to define what are you looking for-"
  else
      for f in $@
      do
         grep -i --color "$f" ./*
      done
    fi
  fi
}

答案 1 :(得分:2)

您可以使用$@表示法拼接${@:2}中从第2开始的所有参数。同时引用"${@:2}",因为您的文件名可以包含空格和任何需要转义的特殊字符。

这应该有效:

function gia() {
if [ -z "$1" ]; then
    echo "-You need to define what are you looking for-"
else
    echo "-Looking for \"$1\".-"
    if [ -z $2 ]; then
        echo "-no path passed, searching all files-"
        grep -i --color "$1" ./*
    else
        echo "-Looking in \"${@:2}\".-"
        grep -i --color "$1" "${@:2}"
    fi
fi
}

<强>输出:

$ gia ABC file*.html
-Looking for "ABC".-
-Looking in "file1.html file 2.html file 3.html file4.html file5.html".-
file 2.html:ABC
file 3.html:ABC
file5.html:ABC