简体   繁体   中英

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

I'm working in a Sencha Touch project. It has js files, that contains lines like:

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. 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 .

Concatenate the extracted parts with 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 .

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. 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. I use hexadecimal digits to write single quotes ( \\x27 ) because the script is surrounded with them too:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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