0
for i in *.jpg
do
    j = '$i | cut -d . -f 1'
    convert $i $j".png"
done

temp.sh: line 3: j: command not found

I know about mogrify, just wanted to know how to get variables done in bash.

4 Answers 4

2

You can also use bash's builtin parameter expansion to remove the first dot and everything after it: j="${i%%.*}"

If you want to remove the last dot and anything following it (i.e. the file's extension), use: j="${i%.*}"

Example:

$ i="file.with.dots.ext"
$ echo "${i%%.*}"
file
$ echo "${i%.*}"
file.with.dots
1
  • And that's probably what he really wants. So for f in ./*.jpg; do convert "$f" "${f%.*}.png"; done.
    – geirha
    Apr 18, 2011 at 7:21
1

You have to remove the spaces around =:

for i in *.jpg
do
    j=`echo $i | cut -d . -f 1`
    convert $i $j".png"
done
3
  • Also, j should've been j=echo $i | cut -d . -f 1 Apr 15, 2011 at 5:51
  • Yes, you're right. I oversaw this. I will update the answer.
    – bmk
    Apr 15, 2011 at 5:53
  • @Shabeer: If you need to use backticks in a comment, prefix these with a backslash (\) as in j=`echo $i | cut -d . -f 1`.
    – Lekensteyn
    Apr 15, 2011 at 7:52
1

In addition, your script won't work as expected if any filename contains any special character (such as a space). You should get in the habit of always enclosing variable references in double quotes. Try this:

for i in *.jpg
do
    j="$(echo "$i" | cut -d . -f 1)"
    convert "$i" "${j}.png"
done
2
  • That will throw an error, unless $i happens to hold a command name. Apr 15, 2011 at 10:32
  • Yes, it's buggy code in ways beyond the double quotes. I see now that the original reply has been edited to include backticks. So, now I have a better idea of what the OP wanted. Without those backticks, the code is incomprehensible, at least to me. I've edited my answer. Apr 15, 2011 at 13:07
0

Integrating bash parameter expansion and double quotes for files with special characters in their names, and the code simplifies too:

for f in *.jpg; do 
    convert "$f" "${f%.*}.png"
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .