How to iterate over a list of files and perform an action on them

command-line-interfaceshell-scripting

I want to write a script (or preferably an alias) that does the following:

  1. Find all the files matching a pattern *.jar
  2. Iterate over all those files, and
    run jar tvf <jar file name> | grep
    <Some argument>
  3. Print if a jar contains a file with a name that matches the argument

I'm working on tcsh and would prefer not to open a new shell since I want this as an alias and not a script – is it doable?

Best Answer

A straight alias isn't going to work for this application. Something like this would come close, except what you would get is the output of the grep, not the jar filename:

alias targrep="find . -name '*.jar' -exec jar tvf {} \; | grep"

targrep someterm

To get the filename, you should switch to using a function instead of an alias so that you have more control over arguments and where values go. (Note: bash format, you may need to modify for tcsh)

function jargrep () {
    find . -name '*.jar' | while read jar; do
        jar tvf $jar | grep -q  $@ && echo $jar
    done
}

jargrep someterm
Related Topic