You are not logged in.

#1 2010-08-05 17:09:50

FerBenzaa
Member
Registered: 2009-01-30
Posts: 32

Cuttin a string in bash

Hi,

I want to cut a string in bash to remove a number in the string, and save that number for further formatting.
At the moment, I am doing it with two double sed's, but I was wondering if it is possible to do it more elegantly.

Here's an example of what I want to do.

Given the String=Agora1.gif

I want to get the the number 1 out of the string.

So, what I am doing is

Number=`echo $String | sed "s/Agora//" | sed "s/\.gif//"`

That will save the number. I can later change the name;

NewName=`printf "Agora%02i" $Number`

and use the new name to rename the original file

mv $String $NewName

I want to do this for a bath of photographs. So far, it works, but I feel that it could be improved.

Offline

#2 2010-08-05 17:28:00

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: Cuttin a string in bash

man rename has an example about this exact same problem.

As for doing it in sed, you should look into using \(, \) and \1, edit: and [0-9]*

Last edited by Procyon (2010-08-05 17:28:46)

Offline

#3 2010-08-05 17:41:50

FerBenzaa
Member
Registered: 2009-01-30
Posts: 32

Re: Cuttin a string in bash

Thanks for the rename command, I didnt know it exists

I'll have a look into \(, \).

Offline

#4 2010-08-05 17:54:01

hbekel
Member
Registered: 2008-10-04
Posts: 311

Re: Cuttin a string in bash

Also note that

NewName=`printf "Agora%02i" $Number`

can be written as:

printf -v NewName "Agora%02i" $Number

This will assign the output of printf to the variable NewName.

Offline

Board footer

Powered by FluxBB