Grzegorz
Grzegorz

Reputation: 107

Bash Command using wildcard as an argument

x=rankings* && grep -A10 -P '^Ranked :$' $x | tail -n +2 > results$x

This is a command that I can't get to work no matter the approach and I haven't been able to find anything within 10+ searches of stack overflow.

Is there a way to feed a wildcard through as an argument to a single line of commands? I want to make a list of files based on existing files in the directory.

The closest I have gotten is

x=rankingsX.Y.Z && grep -A10 -P '^Ranked :$' $x | tail -n +2 > results$x

where X Y Z are some numbers, but this hard-coding individually is the opposite of my objective - a single line command(not script file) that searches and outputs specific text into files using the original names.

Upvotes: 0

Views: 94

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295403

A redirection only has one destination at a time; thus, an attempt to redirect to an expression which, when string-split and glob-expanded, results in more than one filename causes a "bad redirection" error.

What you want is x to have one value at a time, for each value the glob matches to -- which is to say that this is a job for a for loop.

for x in rankings*; do grep -A10 -P '^Ranked :$' "$x" | tail -n +2 >"results$x"; done

...which could also be written over multiple lines (even at an interactive shell), as in:

for x in rankings*; do
  grep -A10 -P '^Ranked :$' "$x" | tail -n +2 >"results$x"
done

Upvotes: 2

Related Questions