Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute command on all files in a directory

Tags:

bash

scripting

Could somebody please provide the code to do the following: Assume there is a directory of files, all of which need to be run through a program. The program outputs the results to standard out. I need a script that will go into a directory, execute the command on each file, and concat the output into one big output file.

For instance, to run the command on 1 file:

$ cmd [option] [filename] > results.out 
like image 241
themaestro Avatar asked May 09 '12 20:05

themaestro


People also ask

How do I run all files in a directory in Linux?

We can run all scripts in a directory or path using "run-parts" command. The run-parts command is used to run scripts or programs in a directory or path. One disadvantage with run-parts command is it won't execute all scripts. It will work only if your scripts have the correct names.

How run multiple files in Linux?

The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds. For example, open a Terminal window (Ctrl+Alt+T in Ubuntu and Linux Mint). Then, type the following three commands on one line, separated by semicolons, and press Enter.


1 Answers

The following bash code will pass $file to command where $file will represent every file in /dir

for file in /dir/* do   cmd [option] "$file" >> results.out done 

Example

el@defiant ~/foo $ touch foo.txt bar.txt baz.txt el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done hello bar.txt hello baz.txt hello foo.txt 
like image 108
Andrew Logvinov Avatar answered Nov 19 '22 10:11

Andrew Logvinov