Grep查找包含目录中字符串的文件

时间:2013-07-08 15:37:48

标签: bash shell grep

我正在努力熟悉终端的基础知识。我想在我的CMS网站中找到包含我的Google Analytics跟踪代码“gaq”的文件,作为搜索字符串应该可以解决问题。

我桌面上有一个包含所有网站文件的文件夹。

  

/用户/ MYNAME /桌面/网站

我打开了终端并尝试了

grep gaq /Users/myname/Desktop/website

grep gaq * /Users/myname/Desktop/website

我在搜索引擎优化和谷歌搜索,但互联网似乎挤出了更高级的grep使用涉及正则表达式和条件。

例如为: Unix Command to List files containing string but *NOT* containing another stringHow can I use grep to find a word inside a folder?

我以为我找到了第二个例子问题的答案。我尝试了以下命令:grep -nr gaq* /Users/myname/Desktop/website

但是这返回了许多结果,而且从我看到的结果来看,我的搜索字符串并不完全准确。

以下是通过查看html页面来源获取的Google Analytics代码段示例。我的目标是找到生成分析代码段的文件,以便将其更新为较新版本的Google Analytics:

var _gaq = _gaq || [];
            _gaq.push(['_setAccount', 'UA-xxxxxxxx-1']);
            _gaq.push(['_trackPageview']);

所以我使用“gaq”作为搜索字符串。

我意识到这听起来非常基本但作为shell的初学者非常令人沮丧。

如何使用grep在目录/ Users / myname / Desktop / website中搜索包含分析代码的文件(返回文件而不是文本的实际段落)(假设grep是我应该使用的命令?)

2 个答案:

答案 0 :(得分:3)

资料来源:man grep

--files-with-matches-l

有一个选项
grep -Rl  gaq /Users/myname/Desktop/website

答案 1 :(得分:3)

Two examples:

   function myFilter(item) {
     for (var columnId in columnFilters) {
        if (columnId != undefined && columnFilters[columnId] !== "") {
             var c = grid.getColumns()[grid.getColumnIndex(columnId)];
             var multiFilters = columnFilters[columnId].split(";");
             var valid=false;
             for(var j=0; j<multiFilters.length; j++){
                 if (multiFilters[j] != undefined && multiFilters[j] != "" && item[c.field] != undefined){
                     if (("" +item[c.field]).toLowerCase().indexOf(multiFilters[j].toLowerCase()) != -1){  
                        valid = true;
                     }
                 }
             }
             if(!valid){
                 return false;
             }
         }
     }
     return true;
 }

What the options mean:

-n, --line-number Prefix each line of output with the 1-based line number within its input file. (-n is specified by POSIX.)

-r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -d recurse option.

-w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore.