简体   繁体   English

Bash:循环遍历目录,查找文件并在连接单词后打印匹配行

[英]Bash: Loop through a directory, find files and print matching lines after concatenation with a word

I'm working in a Sencha Touch project. 我在Sencha Touch项目工作。 It has js files, that contains lines like: 它有js文件,包含如下行:

Ext.define('AssetMenuModel', {
    extend: 'Ext.data.Model',
    config:{    
        fields: ['code','name']
    }
});

We have to iterate the whole JS folder over the files with *.js extension. 我们必须在扩展名为*.js的文件上迭代整个JS文件夹。 We can do this by: 我们可以这样做:

find ./js/common -type f -name "*.js"

Find the line with extend: 'Ext.data.Model' and extract the part: Ext.data.Model . 找到带有extend: 'Ext.data.Model'的行extend: 'Ext.data.Model'并解压缩部分: Ext.data.Model

Concatenate the extracted parts with and include -namespace {Extracted_Part} . 将提取的部分连接起来and include -namespace {Extracted_Part}

And ultimately print the output into a file or to console. 最终将输出打印到文件或控制台。

The output will be something like this 输出将是这样的

and include -namespace Ext.data.Model and include -namespace Ext.Panel . and include -namespace Ext.data.Model and include -namespace Ext.Panel

Thanks in advance. 提前致谢。

尝试:

for i in `find ./js/common -type f -name "*.js"`; do grep "extend: .*," $i | sed "s/.*'\(.*\)'.*/and include -namespace\1/" | tr '\n' ' ' ; done

I suppose that is not needed to check that extend line is inside Ext.define block. 我想不需要检查extend行是否在Ext.define块内。 Otherwise the solution will be far more complex. 否则,解决方案将更加复杂。 This one reads every js file line by line and use a regular expression to find that line and do grouping to extract the string. 这个逐行读取每个js文件,并使用正则表达式查找该行并进行分组以提取字符串。 I use hexadecimal digits to write single quotes ( \\x27 ) because the script is surrounded with them too: 我使用十六进制数字来编写单引号( \\x27 ),因为脚本也被它们包围:

perl -ne '
    if ( m/\A\s*(?i)extend\s*:\s*\x27([^\x27]*)\x27/ ) { 
        printf qq|and include -namespace %s |, $1;
    } 
    END { print "\n" }
' $(find ./js/common -type f -name "*.js")

In my test with two dummy javascript files created in a moment, yields: 在我的测试中,片刻创建了两个虚拟javascript文件,产量:

and include -namespace Ext.data.Model and include -namespace Ext.Panel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM