Score:2

How to remove/add/replace numbers from multiple filenames?

so flag

How to remove and add numbers from multiple filenames?

For example, I want to change the names of filenames Apple1.sh and Banana2.sh to Apple.sh and Banana.sh

I have googled this for a while but I haven't found a precise answer

Found this:

for i in *.sh; do
  echo "$i" | sed 's/^[0-9_ ]*//'
done

But it only displays the output and doesn't change the filenames.

I also need to add numbers, for example, 3 to the renamed filenames so they become Apple3.sh and Banana3.sh still can't find ways to do this.

Bulk renaming that only changes numbers could be helpful too. Like from Apple3.sh and Banana3.sh to Apple4.sh and Banana4.sh

Score:3
hr flag

You can use the Perl-based rename command (available by installing the rename package), ex.:

  • replace a non-empty sequence of digits before a period with nothing

    $ rename -n 's/(\d+)(?=\.)//' *.sh
    rename(Apple1.sh, Apple.sh)
    rename(Banana2.sh, Banana.sh)
    
  • increment a non-empty sequence of digits before a period

    $ rename -n 's/(\d+)(?=\.)/$1+2/e' *.sh
    rename(Apple1.sh, Apple3.sh)
    rename(Banana2.sh, Banana4.sh)
    

The -n option is for testing - remove it when you want to actually rename the files.

hr flag
@Raffa thanks, don't know how I missed that - I had the escape originally, then decided to use a lookahead, and forgot to carry it over
Raffa avatar
jp flag
You're most welcome ... I knew it was a typo, so I fixed it right away ... Nice use of a lookahead positive in the right place BTW ... I don't see these used enough recently :-)
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.