3

I want to add a command line option -r, recurse, to this code:

for name in *.$1; do
    stripped_name="$(basename "$name" ".$1")"
    mv "$name.$1" "$name.$2"
done

So if I enter "change -r txt doc", the command should be executed recursively on any subfolder. For example, if there is a file aaa.txt and a directory y containing files y/bbb.txt and y/ccc.txt....it should result in files aaa.doc, y/bbb.doc and y/ccc.doc.

Also if I don't supply the "-r", it should work as normal.

Does anyone know how to add this to my script?

1 Answer 1

1

I bet this is far from ideal, but how about the following? This uses find to get the files to rename, but if you don't supply the -r, it adds -maxdepth 1 to the arguments. Then it uses the rename(1) command on Debian based systems (e.g. Ubuntu) to rename the matching files. The -print0 and xargs -0 makes sure that this doesn't have problems with odd filenames that might contain newlines, etc.

#!/bin/bash

if [ x"$1" = x-r ]
then
    FIND_OPTIONS=""
    shift
else
    FIND_OPTIONS="-maxdepth 1"
fi

FROM="$1"
TO="$2"

find . $FIND_OPTIONS -name '*.'$FROM -print0 | xargs -0 rename "s/\.$FROM/\.$TO/"
Sign up to request clarification or add additional context in comments.

2 Comments

I was thinking maybe using a "case" to select -r. I'm thinking about writing it that way. What do you think? BTW, thanks for the suggestion and code Mark.
I don't think there's any need to use case here - the -r is either present or not, rather than being one of a several possibilities.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.