Ubuntu – bash command for each file in a folder

bashcommand line

I have a set of files on which I would like to apply the same command and the output should contain the same name as the processed file but with a different extension.

Currently I am doing rename /my/data/Andrew.doc to /my/data/Andrew.txt I would like to do this for all the .doc files from the /my/data/ folder and to preserve the name.

I tried several versions but I guess I have something wrong in the syntax as I an new to linux.

Best Answer

There are at least a hundred thousand million different ways of approaching this but here are the top contenders:

The Bash for loop

for f in ./*.doc; do
    # do some stuff here with "$f"
    # remember to quote it or spaces may misbehave
done

Using find

The find command has a lovely little exec command that's great for running things (with some caveats). Find is better than basic globbing because you can really filter down on the files you're selecting. Be careful of the odd syntax.

find . -iname '*.doc' -exec echo "File is {}" \;

Note that find is recursive so you might want to use -maxdepth 1 to keep find in current working directory. -type f can be used to filter out regular files.

If we're just renaming doc to txt...

The rename command is sed-like in searching. Obviously this won't do anything to convert the format.

rename 's/doc$/txt/' *.doc