adding command line option -r
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 开发者_StackOverflowshould work as normal.
Does anyone know how to add this to my script?
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/"
精彩评论