70

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.

1

2 Answers 2

138

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
2
  • 2
    For the for..loop example: I noticed that if there are no files in the subdirectory ./*.doc then the loop is executed anyway with the string "./*.doc". It's probably a good idea to check if $f is a file: if [ -f $f ]; then ... fi
    – arod
    Aug 19, 2020 at 14:07
  • But then with for f in "$TEST_DIR/input*.txt"; do if [ -f $f ] then I get error binary operator expected if files do exist Jul 23, 2023 at 8:47
33
for i in *.doc ; do mv "$i" $(echo $i | sed s/doc/txt/) ; done
1
  • 4
    In 'sed', you have to replace 'doc' by 'doc$' (ends with 'doc') to prevent issue with names like "doc_doc.doc" which result in "txt_doc.doc". => sed s/doc$/txt/ Aug 6, 2020 at 12:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .