Results 1 to 3 of 3

Thread: Renaming files, based on calculations

  1. #1
    Join Date
    Mar 2007
    Location
    Portsmouth, UK
    Beans
    Hidden!
    Distro
    Ubuntu 11.10 Oneiric Ocelot

    Renaming files, based on calculations

    Greetings!

    I'm often renaming directories of files using a loop, and sed - as I'm sure many of us do; what I want to do now is rename files while performing basic subtraction on the numerals at a location in the file name.

    Code:
    files19.subfile9.2323.txt
    files19.subfile9.2324.txt
    files19.subfile9.2325.txt
    I would like to subtract 49 from each file (there are thousands), so that the names are:

    Code:
    files19.subfile9.2274.txt
    files19.subfile9.2275.txt
    files19.subfile9.2276.txt
    I've been trying various things, and it was getting more convoluted by the minute.

    Could anyone suggest an elegant way to go about this?

  2. #2
    Join Date
    Feb 2009
    Location
    Dallas, TX
    Beans
    7,790
    Distro
    Ubuntu 16.04 Xenial Xerus

    Re: Renaming files, based on calculations

    Hi Grenage.

    I would use parameter substitution instead of 'sed'.

    For instance:
    Code:
    $ file="files19.subfile9.2325.txt"
    $ bname=${file%.txt}
    $ echo $bname
    files19.subfile9.2325
    
    $ number=${bname##*.}
    $ echo $number
    2325
    
    $ newnumber=$(($number-49))
    $ echo $newnumber
    2276
    
    $ newfile=${bname%.*}."$newnumber".txt
    $ echo $newfile
    files19.subfile9.2276.txt
    Hope it helps.
    Regards.

  3. #3
    Join Date
    Mar 2007
    Location
    Portsmouth, UK
    Beans
    Hidden!
    Distro
    Ubuntu 11.10 Oneiric Ocelot

    Re: Renaming files, based on calculations

    Perfect, that's a good way of getting it done; thanks a lot.

Bookmarks

Posting Permissions

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