for ... do ... done

Tricks and tips for new and novice UNIX and Linux users. Please feel free to add your own favourite command or tip here.

for ... do ... done

Postby chaosd » Tue Jul 18, 2006 1:29 pm

One of the things I missed about MS-DOS was being able to do:
Code: Select all
ren foo* foo*.bar

In Unix you need to do:
Code: Select all
for x in foo*; do mv $x $x.bar; done

The first part of this: 'for x', tells unix that we want to process a list of 'things' - essentially words or numbers - and that we will refer to each individual 'thing' as 'x'. In technical terms we are defining a variable which we have called x.
Next we use 'in foo*' to define our list. Unix 'just knows' that foo* means "all the files starting with 'foo'". The ';' tells unix we have finished defining our list.
do mv tells Unix what we want to do with each item (x).
$x refers to the variable contents. Once again, Unix 'just knows' that there is no variable called x.bar, and so correctly appends .bar to the file name held in the variable x.
Lastly, ; done indicates to Unix that we have finished entering our command.
So, if we had three files, foo1, foo2 and foo3, our command would be the same as typing:
Code: Select all
mv foo1 foo1.bar
mv foo2 foo2.bar
mv foo3 foo3.bar
There are no stupid questions
chaosd
 
Posts: 61
Joined: Tue Dec 07, 2004 2:33 pm
Location: Redditch || Blockley (UK)

Advertisement

Consolidating directories

Postby chaosd » Wed Jul 19, 2006 10:56 am

Ok, for ... do ... done may seem a little excessive to rename a group of files, but the basic concept can be used for many more things.
For example:-
Code: Select all
for x in /foo/*; do cp $x/* ./; done

would copy the files from all the sub-directories under /foo/ to the current directory.
One small problem with this is that if the same filename is used in two or more directories, each new version will over write the previous copy. However, the cp command can be made to make numbered backups of existing files, so our command becomes:
Code: Select all
for x in /foo/*;do cp --backup=numbered $x/* ./;done
There are no stupid questions
chaosd
 
Posts: 61
Joined: Tue Dec 07, 2004 2:33 pm
Location: Redditch || Blockley (UK)


Return to Tips and Tricks - beginners / novice

Who is online

Users browsing this forum: No registered users and 1 guest

cron