[oclug] filename renaming
Bart Trojanowski
bart at jukie.ca
Tue Sep 20 21:39:46 EDT 2011
The regexp here looks quite illegible. How about...
(
cd Pictures
for jpg in */*.jpg ; do
dir="$(dirname "$jpg")"
name="$(basename "$jpg")"
mv "$jpg" "$dir/${dir}_$name"
done
)
As an added bonus this will work with any characters in the file name.
Another way of doing the same thing in just shell...
(
cd Pictures
for jpg in */*.jpg ; do
dir="${x%/*}"
name="${x##*/}"
mv "$jpg" "$dir/${dir}_$name"
done
)
... but that's getting back to the same problem the sed had.
-Bart
On Tue, Sep 20, 2011 at 16:56, Woogie <woogie at gmail.com> wrote:
>
> Using this bit of bash and sed worked for me. It might choke on funky
> characters, though
>
> I used "Pictures" as my example directory:
>
> for x in `ls Pictures/*` ; do
> DIR_NAME=$(echo $x | sed -e 's|\([^/]*\)/.*|\1|')
> FILE_NAME=$(echo $x | sed -e 's|[^/]*/\(.*\)|\1')
> echo "${DIR_NAME}_${FILE_NAME}"
> done
>
> The first line iterates over all the file names in "Pictures" in the
> form "Pictures/filename.jpg"
> The second line uses sed to assign the variable DIR_NAME the name of
> the directory
> The third line uses sed to assign the variable FILE_NAME the name of the file
> The fourth line just echoes the form of the filename you wanted. You'd
> replace this line with a cp or mv, at your leisure. Remember, $x holds
> the path to the file
> The fifth line terminates the loop
>
> This is quick and dirty; odds are there are programs out there you
> could chain together to get the same results without resorting to
> using sed.
>
> Woogie
>
> On Tue, Sep 20, 2011 at 4:38 PM, Normand Fisher <fishern at ncf.ca> wrote:
> > I'd like to have a script to rename groups of files by including the
> > directory name in the revised filename.
> >
> > Ex: in directory "A", I have files 1, 2, 3, 4, and 5.
> > I would like to rename the files to A_1, A_2, A_3, A_4 and A_5.
> >
> > To do this, I have so far used the "mmv" command but I still have to
> > type in the directory name for each batch. Is there a way to capture
> > the directory name and place it in a variable?
> > I have looked at "pwd" but that gives me the whole path.
> >
> > I don't mind using command line but I am not a programmer. Any
> > suggestion is welcome.
> >
> > Normand
> > --
> > OCLUG general discussion list
> > OCLUG at lists.oclug.on.ca
> > http://oclug.on.ca/mailman/listinfo/oclug
> >
>
>
>
> --
> Evil will always triumph, because good is dumb
> --
> OCLUG general discussion list
> OCLUG at lists.oclug.on.ca
> http://oclug.on.ca/mailman/listinfo/oclug
More information about the OCLUG
mailing list