2

I need to write a shell script.

-for example

my files:

daily.gfr.gif, abc.gif , def.gif , fgr.gif , fgt.gif , current.abc.gif

I want to change as below:

1_daily.gfr.tlf , 2_abc.tlf , 3_def.tlf , 4_fgr.tlf , 5_fgt.tlf , 6_current.abc.tlf

I write a script:

for file in *.gif
do
    filename=$(basename "$file")
    filename=${filename%.*}
    convert $file $filename.tlf
done

Is this right in your opinion? How can I add name changing?

2
  • 1
    Notes: (1) The names are listed in a different order than will be generated by *.gif; the names will be generated in alphabetic order. (2) The basename operation does nothing. You could have written filename=$(basename "$file" .gif) to remove the suffix, or you can do what you do on the next line. (3) You need a counter and an increment operation: counter=1 outside the loop, ${counter}_$filename.tlf as the second argument to convert, and ((counter++)) or similar to increment the counter. Commented Oct 12, 2013 at 23:10
  • 3
    Please don't deface your questions after people have taken the time to answer them. This isn't fair to people trying to answer you. Commented Oct 15, 2013 at 1:07

2 Answers 2

3
nr=0
for file in *.gif; do
    nr=$(($nr+1))
    filename="$(basename "$file")"
    filename="${filename%.*}"
    convert "$file" "${nr}_$filename.tlf"
done
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget the quotes.
1

If you're going to use the basename command instead of parameter expansions, you should use it to its fullest power by giving it an extension suffix to drop. That will take care of both birds with one stone.

nr=0
for file in *.gif; do
  filename="$(( ++nr ))_$(basename "$file" .gif).tlf"
  convert "$file" "$filename"
done

You could also do the whole thing with parameter expansion:

nr=0
for file in *.gif; do
  filename="$(( ++nr ))_${file##*/}"
  filename="${filename%.*}"
  convert "$file" "$filename"
done

The benefit of the parameter expansions is that you don't invoke a subshell every iteration. Unless you need to process a lot of files, it won't make a difference.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.