Gerry Lufwansa
Gerry Lufwansa

Reputation: 13

How to perform "map" in bash?

I'd like to add a bunch of directories to a command-line program, where each directory is supplied to a command-line option:

% cmd -I dir1 -I dir2 -I dir3 -I dir4 -I dir5

Suppose I can express the directories as a wildcard, is there a way to interleave it with "-I" in a single command? For example, in Ruby I can do:

system ["cmd", *Dir["dir*"].collect {|d| ["-I", d]}.flatten(1) ];

or, more succinctly in Perl:

system "cmd", map {("-I", $_)} <dir*>;

Upvotes: 1

Views: 1188

Answers (2)

Varun
Varun

Reputation: 477

you can use

for i in dir{1..4}; do value=$value" -I $i"; done; cmd $value

Upvotes: 0

choroba
choroba

Reputation: 241918

With directory names not containing whitespace, you can use parameter substitution

dirs=(dir*)
cmd ${dirs[@]/#/-I }

/# means "substitute at the beginning".

If the space after -I is not needed, you can use brace expansion (works with dirnames containing whitespace):

cmd -I'dir'{1..5}

This works with long options that use the equal sign, too:

cmd --capital-i=dir{1..5}

Upvotes: 4

Related Questions