LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   string substitution (http://www.linuxquestions.org/questions/programming-9/string-substitution-855796/)

lipun4u 01-12-2011 06:07 AM

string substitution
 
just look into the following code...


Code:

#!/bin/sh
set -x


if [ $# -ne 3 ]
then
        echo "Usage : $(basename $0) <path> <from ext> <to ext>"
        exit 0
fi

direct=${1}
from_ext=.${2}
to_ext=${3}

for file in ${direct}/*
do
        filename=${file%%'${from_ext}'}
        if [ ${filename} != $file ]
        then
                mv ${file} ${filename}.${to_ext}
        fi 
done


the code is supposed to move all files with first extension(2nd arg) to the 2nd extension(3rd arg).

Wht's wrong in the code ??

grail 01-12-2011 08:18 AM

Please explain the following line:
Code:

filename=${file%%'${from_ext}'}

Reuti 01-12-2011 08:27 AM

BTW: there is also the command rename, which can rename files based on a pattern.

catkin 01-12-2011 11:06 AM

BTW you don't need any of the { } around variable names except for the outermost in ${file%%'${from_ext}'}.

Grail's question will lead to a solution.

H_TeXMeX_H 01-12-2011 11:50 AM

I don't like string substitution syntax, it looks obscure, instead I would use basename in this way:

Code:

mv "$i" "$(basename "$i" .avi).mkv"
from .avi to .mkv, real simple and readable, this is what I always use.

Now, of course, I don't use this to batch rename things, I use rename. Instead I use this when converting formats with ffmpeg.

lipun4u 01-12-2011 02:10 PM

Quote:

filename=${file%%'${from_ext}'}
it will remove the content of from_ext at the end of file

Reuti 01-12-2011 02:23 PM

Did you test this expression on the command line and got the desired result?

lipun4u 01-12-2011 02:54 PM

nop...i am confused..

crts 01-12-2011 03:26 PM

Quote:

Originally Posted by lipun4u (Post 4222039)
it will remove the content of from_ext at the end of file

As a further hint you might want to read up about the difference of single and double-quotes when using bash.

grail 01-12-2011 06:34 PM

Ahhhh ... crts with the spoiler :)

crts 01-12-2011 08:12 PM

It wasn't a total spoiler ...
 
... I merely gave a hint and which will also help the OP with the other problematic lines.
I'm just saying: whitespace

So there is still plenty of fun left for the OP :)

grail 01-13-2011 01:47 AM

Nice work as always crts ;)


All times are GMT -5. The time now is 06:53 PM.