shell脚本中的grep实用程序

问题描述:

我试图克服对我们文件结构的限制。我想在一个已知位置grep一系列文件。如果我从命令行执行标准grep

I'm trying to overcome a limitation on our file structure. I want to grep a whole series of files in a known location. If I do a standard grep from command line

(grep -i searchpattern known_dir/s*.sql) 

我收到以下错误消息:

I get the following error:

ksh: /usr/bin/grep: 0403-027 The parameter list is too long.

所以我有一个for循环,看起来像:

so I have a little for loop that looks like:

searchfor=$1
for i in /$ENV_VAR_DIR/s*.sql
do
  grep -i $searchfor $i
done

当我执行此操作时,我遇到了一些问题:

When I execute this I get a couple problems:


  1. 它为我提供了一行代码,但没有文件名,我需要这两行

  2. -l 显然给了我路径/文件名我想修剪路径,我只是从我的主目录执行。


我会推荐以下内容:

$ find known_dir -name 's*.sql' -print0 | xargs -0 grep -i searchpattern

使用 xargs ,每次使用 -n 选项时,可以改变传递给 grep 的最大文件数量。

With xargs, you can vary the maximum number of files you pass to grep each time using the -n option.

-print0 -0 选项可以防御空格在文件名中。

The -print0 and -0 options is a defense against spaces in filenames.

甚至可以使用 grep > -P 选项。

You could even compute multiple grep commands in parallel on multiple cores using -P option.