user3263699
user3263699

Reputation: 51

Looping through directories

I have a directory structure like and I am looping through directories like but getting error that could not find the directory any idea? In the first dir it is looking for dir1 dir2 dir3 and so on and in the second dir1 it is looking for dirA dir B and dirC Thanks.

   ./subtle1/
        /fooA/file.txt
        /fooB/file.txt
        /fooC/file.txt

   ./subtle2/
     /fooA/file.txt
     /fooB/file.txt
     /fooC/file.txt

for i in ~/new/subtle*;
       do
               if [ -d "$i" ] ; 
then
       cd $i

    for j in "$i"/foo* ; do

                if [ -d "$j" ] ; 
 then
       cd $j
            mv file.txt $i.$j.file.txt
 done
 done

Upvotes: 0

Views: 86

Answers (3)

pawel7318
pawel7318

Reputation: 3573

If you really want to do this by a script and use cd to walk around than try this:

#!/bin/bash

for sub in subtle*; do
  if [ -d "${sub}" ]; then
    cd ${sub}
    for foo in foo*; do
      if [ -d "${foo}" ]; then
        cd ${foo}
        pwd
        echo mv -- file.txt ${sub}.${foo}.file.txt
        cd ..
      fi
    done
    cd ..
  fi
done 

you can remove pwd and echo to just execute mv.

Upvotes: 0

pawel7318
pawel7318

Reputation: 3573

If you want to just change the filenames that way:

mv ./subtle1/fooB/file.txt ./subtle1/fooB/subtle1.fooB.file.txt
mv ./subtle1/fooA/file.txt ./subtle1/fooA/subtle1.fooA.file.txt
mv ./subtle1/fooC/file.txt ./subtle1/fooC/subtle1.fooC.file.txt
mv ./subtle2/fooB/file.txt ./subtle2/fooB/subtle2.fooB.file.txt
mv ./subtle2/fooA/file.txt ./subtle2/fooA/subtle2.fooA.file.txt
mv ./subtle2/fooC/file.txt ./subtle2/fooC/subtle2.fooC.file.txt

than all you need is:

find -type f -print|sed -r -e 's/\.\/(.+)\/(.+)\/(.+)/\0 .\/\1\/\2\/\1.\2.\3/'|xargs -n 2 mv

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272217

One problem that strikes me immediately is that you cd within a loop, and you don't come out of that directory for the next iteration.

So you'll cd into ~/new/subtle1/fooA, do some work, and then for the next iteration you're already in that directory, whereas you want to be at your original (starting) point.

I would check out pushd/popd. pushd works like cd, but it maintains a stack of visited directories, and popd will take you back in that stack.

e.g.

$ pwd
/home/brian

$ pushd /var/log
$ pwd
/var/log

$ popd
$ pwd
/home/brian

Upvotes: 1

Related Questions