Shell Script for end character rename

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
jrskero

Shell Script for end character rename

Post by jrskero »

I would like to rename a1b2c3b4pp987.txt to only use the last 5 charcters plus extension pp987.txt
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
User avatar
Pilosopong Tasyo
Level 6
Level 6
Posts: 1432
Joined: Mon Jun 22, 2009 3:26 am
Location: Philippines

Re: Shell Script for end character rename

Post by Pilosopong Tasyo »

jrskero wrote:I would like to rename a1b2c3b4pp987.txt to only use the last 5 charcters plus extension pp987.txt
Refer here for some clues.

<off topic>
Why do I have the feeling this is a homework question? :shock:
I'm just sayin'
</off topic>
o Give a man a fish and he will eat for a day. Teach him how to fish and he will eat for a lifetime!
o If an issue has been fixed, please edit your first post and add the word [SOLVED].
User avatar
catweazel
Level 19
Level 19
Posts: 9763
Joined: Fri Oct 12, 2012 9:44 pm
Location: Australian Antarctic Territory

Re: Shell Script for end character rename

Post by catweazel »

jrskero wrote:I would like to rename a1b2c3b4pp987.txt to only use the last 5 charcters plus extension pp987.txt

Code: Select all

#!/bin/bash
mv a1b2c3b4pp987.txt pp987.txt
ls
HTH
"There is, ultimately, only one truth -- cogito, ergo sum -- everything else is an assumption." - Me, my swansong.
User avatar
xenopeek
Level 25
Level 25
Posts: 29511
Joined: Wed Jul 06, 2011 3:58 am

Re: Shell Script for end character rename

Post by xenopeek »

Making that a bit more flexible (note this is hacked together and only works for files in your current directory that have a three letter extension):

Code: Select all

#!/bin/bash
file="a1b2c3b4pp987.txt"
mv $file ${file: -9}
Or more flexible, letting you run the command with the name of file you want to rename as an argument (so "./scriptname a1b2c3b4pp987.txt"):

Code: Select all

#!/bin/bash
mv $1 ${1: -9}
Or if you want to do that for all .txt files in the current directory, just run the following one command :wink:

Code: Select all

for file in *.txt; do mv $file ${file: -9}; done
Image
jrskero

Re: Shell Script for end character rename

Post by jrskero »

Worked perfect thanks!!
Locked

Return to “Scripts & Bash”