Find the answer to your Linux question:
Results 1 to 5 of 5
Hello, I am trying to write a script that renames files a certain way. For example, if the input is " ren '*a' '*b' " all files in the current ...
  1. #1
    Just Joined!
    Join Date
    Apr 2008
    Location
    California
    Posts
    3

    Need help renaming files a certain way

    Hello,

    I am trying to write a script that renames files a certain way. For example, if the input is " ren '*a' '*b' " all files in the current directory that end with a would end with b instead.

    Here's what I have so far:

    Code:
    #!/bin/bash
    
    for f in *$1; do
      j=${f%$1}$2
      mv $f $j
    done

    However, it is not working properly. What it does is it renames the files to the second arg. How can I fix it?

    EDIT: well, it kinda works, but not fully. If a filename is "test" and I do " ren '*st' '*aa' " the result becomes "te*aa" instead of just "teaa". How to get rid of the *?

    Thank you for your help!

  2. #2
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    Untested, but you should strip the * from the second argument:

    Code:
      j=${f%$1}${2/\*/}

  3. #3
    Just Joined!
    Join Date
    Apr 2008
    Location
    California
    Posts
    3
    Thanks for your help! I played around with it and this seemed to work for me:

    Code:
    #!/bin/bash
    
    tmp=$(echo $2 | tr -d "*")
    
    for f in *$1; do
      j=${f%$1}$tmp
      mv $f $j
    done

  4. #4
    drl
    drl is offline
    Linux Engineer drl's Avatar
    Join Date
    Apr 2006
    Location
    Saint Paul, MN, USA / CentOS, Debian, Solaris, SuSE
    Posts
    1,117
    Hi.

    If you are interested in a more general renaming utility, see mved

    It uses "=" as an additional meta-character to provide flexibility in specifying patterns of strings ... cheers, drl
    Welcome - get the most out of the forum by reading forum basics and guidelines: click here.
    90% of questions can be answered by using man pages, Quick Search, Advanced Search, Google search, Wikipedia.
    We look forward to helping you with the challenge of the other 10%.
    ( Mn, 2.6.n, AMD-64 3000+, ASUS A8V Deluxe, 1 GB, SATA + IDE, Matrox G400 AGP )

  5. #5
    Just Joined!
    Join Date
    Apr 2008
    Location
    California
    Posts
    3
    After testing my script for a bit, I found out that it renames folders as well as files. I would like to add an option/flag/argument so that I can use this way to rename both folders and files:

    Code:
    ren '*st' '*aa'
    ...and this way to rename files only:

    Code:
    ren -f '*st' '*aa'
    How can I go about ignoring folders this way?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...