Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change to all direcories and do some work inside them --script 4

Status
Not open for further replies.

omasnjak

Technical User
Jun 1, 2008
13
CZ
Hi all,

I want to make some script which will cd to all direcories in some directory and do something there....

let say I have

dir1
dir2
dir3
dir4

and inside all those directories, some .txt files
I made this
for i in $(ls) ;do cd $i; cd $(date +%d_%m_%Y); cat *.txt; echo " we are now in $i and $(date +%d_%m_%Y)";sleep 5; done
When I run above code it just change to first one, and cat .txt files in that dir.
I tried many options, but did not get result I want.

Any hint is welcome.

Regards,


 
That's because when you've finished doing 'stuff' in each directory, and before you exit the loop, you have to cd .. back to the parent directory before you iterate to the next one in the loop...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Some alternatives to manualy CD-ing trough the directories:

1. cd itself has the capabilities to recursively traverse
directories, check the -R option.

2. Use find to locate the wanted files, and do the job.
Code:
find /path/to/parentdir -name "*\.txt" -exec yourscripthere {} \;
or pipe the output to xarg and use it to processe located files.

man ls
man find


HTH
:)
 
Oops, sorry.
Alternative 1 should read:

1. ls itself has the capabilities to recursively traverse
directories, check the -R option.
 
Using a separate script and find is sometimes an easy solution but in this case ...
Even ls is not needed.
Code:
for f in dir?/$(date +%d_%m_%Y)/*.txt ; do cat $f; echo "we are in paradise at"$(date +%d_%m_%Y) ; sleep 1; done

don't visit my homepage:
 
I Would write it something like this:

for i in $(ls) ;do
pushd .
cd $i
cd $(date +%d_%m_%Y)
cat *.txt
echo " we are now in $i and $(date +%d_%m_%Y)"
popd
sleep 5
done

"pushd ." saves in which directory you are in, then you can cd many times without keeping track of it, and "popd" changes back to the directory pushd was executed in.

If you like you can combine "pushd ." and "cd $i" to a single row "pushd $i". A more compact version:

for i in * ;do
if [ -d $i/$(date +%d_%m_%Y) ]; then
pushd $i/$(date +%d_%m_%Y)
cat *.txt
echo " we are now in $i and $(date +%d_%m_%Y)"
popd
sleep 5
fi
done
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top