Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I execute the command for each result of the file globbing in zsh without for?

I am searching for away to execute the current command for each result of the file globbing without building a for loop. I saw this somewhere but can't remember where exactly.

(The echo is just an example, it should also work with psql for example)

Example:

$ touch aaa bbb ccc ddd
$ echo "--- " [a-c]*
---  aaa bbb ccc

Desired output:

---  aaa
---  bbb
---  ccc

Kown way:

$ for i in [a-c]*; do echo "--- " $i ; done
---  aaa
---  bbb
---  ccc

Could be done using for. But maybe there is a way to do it shorter? Maybe like using double curly braces around the glob or whatever?

Thanks. :)

like image 803
Benjamin Peter Avatar asked Oct 13 '11 07:10

Benjamin Peter


2 Answers

You may be looking for zargs, a command with the same purpose as xargs but a saner interface.

autoload -U zargs
zargs -n 1 -- * -- mycommand
like image 105
Gilles 'SO- stop being evil' Avatar answered Sep 23 '22 14:09

Gilles 'SO- stop being evil'


The printf command will implicitly loop if given more arguments than placeholders in the format string:

printf -- "--- %s\n"  [a-c]*

To execute a command on each file, you need xargs: I assume you have GNU xargs that has the -0 option:

printf "%s\0" [a-c]* | xargs -0 -I FILE echo aa FILE bb

Replace the echo xargs command with whatever you need, using the "FILE" placeholder where you need the filename.

Use your own judgement to determine if this is actually better or more maintainable than a for-loop.

like image 27
glenn jackman Avatar answered Sep 24 '22 14:09

glenn jackman