Results 1 to 6 of 6

Thread: Reverse filename

  1. #1
    Join Date
    Jan 2006
    Beans
    279
    Distro
    Ubuntu 22.04 Jammy Jellyfish

    Reverse filename

    Hi,
    Is there an easy way to reverse filenames? Example: abcdef.jpg becomes fedcba.jpg.

  2. #2
    Join Date
    Apr 2012
    Beans
    7,256

    Re: Reverse filename

    You can use the rev command

    Code:
    DESCRIPTION
         The rev utility copies the specified files to standard output, reversing
         the order of characters in every line.  If no files are specified, stan‐
         dard input is read.
    If you don't want to reverse the suffix as well, you will need to remove and replace it e.g.

    Code:
    $ f="abcdef.jpg"
    $ 
    $ r="$(rev <<< "${f%.*}").${f##*.}"
    $ 
    $ echo "$r"
    fedcba.jpg

  3. #3
    Join Date
    Jan 2006
    Beans
    279
    Distro
    Ubuntu 22.04 Jammy Jellyfish

    Re: Reverse filename

    Thanks for mentioning the rev command. Does it actually reverse the filename on disk (this it what I want), or does it simply make a string of the reverse characters?

  4. #4
    Join Date
    Jul 2007
    Location
    Poland
    Beans
    4,499
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: Reverse filename

    it's a string that can be plugged into mv command, thus solving your problem

    in steeldriver's example it would be
    Code:
    mv "$f" "$r"
    if your question is answered, mark the thread as [SOLVED]. Thx.
    To post code or command output, use [code] tags.
    Check your bash script here // BashFAQ // BashPitfalls

  5. #5
    Join Date
    Jan 2006
    Beans
    279
    Distro
    Ubuntu 22.04 Jammy Jellyfish

    Re: Reverse filename

    Thanks for explaining, vaphell.
    Is there a way to combine the rev and mv command in one command that I could reuse, while simply replacing the filename?

  6. #6
    Join Date
    Apr 2012
    Beans
    7,256

    Re: Reverse filename

    Well you could just do a "one-liner" to loop over the list of files, like

    Code:
    for f in *.jpg; do echo mv "$f" "$(rev <<< "${f%.*}").${f##*.}"; done
    However I thought about this some more in the meantime - since Ubuntu provides the perl-based rename command, and perl has its own string reverse function, you should be able to do something like

    Code:
    rename -vn -- 's/(.*)[.]([^.]*)$/join(".",my $rev=reverse($1),$2)/e' *.jpg
    abcdef.jpg renamed as fedcba.jpg
    pqrstu.jpg renamed as utsrqp.jpg
    The -n option is only for testing purposes.
    Last edited by steeldriver; June 29th, 2014 at 06:43 PM.

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
  •