running for loops on command line

This is one of the most important Linux skill to master ever! It can help you try a bunch of parameters, do something for all the files in the directory … improve your efficiency significantly if mastered.

Here are a few examples

(1) Process every file in the directory

The basic format

for f in *; do 

   process each $f;

done

An example: use Python plotHist.py on every output file,

for f in *.out; do python plotHist.py $f; done

A reference post http://askubuntu.com/questions/315335/bash-command-for-each-file-in-a-folder

(2) Trying different parameters

The basic format

for i in  1 2 4;  do echo $i; done

This prints 1 2 4

To only specify the beginning and the end range,

for i in {1..5}; do echo $i; done

An actual example would be

for i in {15..21}; do head -n 1  “data/file_${i}.txt”; done

This would display the first line for file_15 to file_21. 

One other useful trick is to iterate through all the files in the directory in one line and do something with every file ,

for file in /path/to/directory/*; do echo $file; cat $file; done

if it is the current directory, just do the following

for file in ./*; do echo $file; cat $file; done

Advertisements
This entry was posted in Tools, Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s