Re: shell scrpt to rename
- From: fiedlert@xxxxxxxxx
- Date: 22 Mar 2006 03:24:31 -0800
How is someone who does not write shell script to begin with supposed
to extraoplate the awnser to his question from the following?
23. How do I rename *.foo to *.bar?
Naive examples in ksh/bash (which may or may not work many times)
$ ls *.foo | while read f;do mv "$f" "${f%.*}".bar
More generically
$ ls *.foo | while read f;do mv "$f" `basename "$f" .foo`.bar
However, these examples contain a potentially unnecessary use of
ls (ie, if the number of files is small enough to not overflow the
command line buffer), and will fail if any file names contain a
newline, or if there are leading or trailing spaces. An
alternative is:
for file in *.foo
do
mv -- "$file" "`basename -- \"$file\" .foo`.bar"
done
Also, tests for existence of files should also be incorporated,
e.g.:
for file in ./*.foo
do
newfile=`basename "$file" .foo`.bar
[ -f "$file" ] || continue
[ -f "$newfile" -o -d "$newfile" ] && continue
mv "$file" "$newfile"
done
In some linux distributions you may be able to use the rename
command
$ rename .foo .bar *
If not (Debian, for one, comes with a perl version of rename that
won't work with that command line) try
$ rename 's/.foo/.bar/' *.foo
More options, and much more discussion about this, is available
from http://www.faqs.org/faqs/unix-faq/faq/part2/section-6.html
Note that for file specifications which don't match existing
files, the shell usually responds with something like "ls: *.foo:
No such file or directory", which will mess up your processing of
file names. One possibility is
#! /bin/sh
set x [*].foo ./*.foo
case "$2$3" in
"[*].foo./*.foo") ;;
*)
shift 2
for file
do
repl=`basename "$file" .foo`.bar
mv "$file" "$repl"
done;;
esac
Except that contrary to (zsh) mmv or zmv it doesn't check for
file overwriting and fails for filenames with NLs before the "."
and doesn't handle dotfiles.
.
- References:
- shell scrpt to rename
- From: rao
- Re: shell scrpt to rename
- From: Chris F.A. Johnson
- shell scrpt to rename
- Prev by Date: Re: shell scrpt to rename
- Next by Date: Re: shell scrpt to rename
- Previous by thread: Re: shell scrpt to rename
- Next by thread: Re: shell scrpt to rename
- Index(es):
Relevant Pages
|