Alex
Alex

Reputation: 355

Run a specific loop in different directories

I have a loop that I want to run in different directories/folders. The directory names are: a, b, c, d, e, ...

My loop is:

cd */
for i in Test_*_hit.txt; do cut -f1,2 $i > ${i%.txt}2.txt; done

But is not working (No such file or directory), how can I do?

Upvotes: 0

Views: 24

Answers (2)

user5920214
user5920214

Reputation:

There are a bunch of ways to do this, but one (Bourne shell) approach is

for d in <directories>
do
  (cd "$d" && <commands>)
done

This uses a subshell (the stuff in parens) to change directory & do what you want to do in that directory, which avoids the effort of having to remember which directory you were in.

Upvotes: 2

Alistra
Alistra

Reputation: 5195

for i in a b c d e
do
    (cd $i/; for i in Test_*_hit.txt; do cut -f1,2 $i > ${i%.txt}2.txt; done)
done

Upvotes: 3

Related Questions