7

I have a bunch of files in a directory all named YYYY_MM_DD

-rw-r--r-- 1 root root 480K Apr 21 13:17 2012_04_05
-rw-r--r-- 1 root root 483K Apr 21 13:17 2012_04_06
-rw-r--r-- 1 root root 484K Apr 21 13:17 2012_04_07
-rw-r--r-- 1 root root 480K Apr 21 13:17 2012_04_08
-rw-r--r-- 1 root root 344K Apr 21 13:17 2012_04_09
-rw-r--r-- 1 root root  66K Apr 21 13:17 2012_04_10
-rw-r--r-- 1 root root 461K Apr 21 13:17 2012_04_11
-rw-r--r-- 1 root root 475K Apr 21 15:09 2012_04_17
-rw-r--r-- 1 root root 480K Apr 21 15:10 2012_04_18
-rw-r--r-- 1 root root 474K Apr 21 15:10 2012_04_19
-rw-r--r-- 1 root root 474K Apr 21 15:10 2012_04_20

I have a shell script that accepts a file as a paramater and calculates figures based on the data in the file, i call the script like this

sh Calculate.sh MyFile

I want to run this shell script for every file in this directory.

How would i go about doing this, xargs ??

Telemachus
  • 19,459
  • 7
  • 57
  • 79
general exception
  • 4,202
  • 9
  • 54
  • 82
  • The `find` command will probably be a good start. Here are a few resources on it: http://www.grymoire.com/Unix/Find.html and http://mywiki.wooledge.org/UsingFind (gets much more complicated, but worth a look at some point). – Telemachus Apr 21 '12 at 14:51

4 Answers4

7

Have you tried the find command with execution ?

My sample will echo the files, but you can call a shell script with the filename as a parameter

find . -maxdepth 1 -type f -exec echo {} \;
Telemachus
  • 19,459
  • 7
  • 57
  • 79
MrJames
  • 676
  • 2
  • 8
  • 20
  • This is cool, but how would i pass them files to my Calculate.sh script in order ??? – general exception Apr 21 '12 at 17:27
  • 2
    Ok.. in that case you need to sort out all the files before calling the script. Try something like this `find . -maxdepth 1 -type f | sort | xargs -I '{}' Calculate.sh '{}'` – MrJames Apr 21 '12 at 17:51
  • I understand the command upto xargs, i understand that sort pipes the data into xargs, what is the -I switch and why is there two of '{}' ?? Many thanks. – general exception Apr 21 '12 at 18:11
  • When using `-I` you can specify a replace-string. The `'{}'` on `find` command represents the current filename returned, but on `xargs` it doesn't have a special meaning because you can run the script with `find . -maxdepth 1 -type f | sort | xargs -I 'recei_param' echo 'recei_param'` and the output will be the same. You can check more details at [man xargs](http://linux.die.net/man/1/xargs) – MrJames Apr 22 '12 at 12:25
6

A simple for loop in the shell:

for file in *; do sh Calculate.sh "$file"; done
Joe
  • 41,484
  • 20
  • 104
  • 125
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

find . -maxdepth 1 -type f | xargs -n 1 -I % Calculate.sh %

Dagang
  • 24,586
  • 26
  • 88
  • 133
1
./Calculate.sh 2012_04_{05..20}
user unknown
  • 35,537
  • 11
  • 75
  • 121