File name manipulation with shell scripts: changing file extensions
shell
Solution
This should work for you:
#!/bin/bash
for file in *.png
do
filename=$(basename "$file")
filename=${filename%.*}
convert $file $filename.tif
done
A line-by-line walkthrough of how this works:
- `for file in *.png` - you don't need command substitution `ls *.png` to get the list of files with `png` extension. The wildcard `*` will auto-expand in shell to match the list of files in cwd; and in this case the list of files ending in `.png`.
- `filename=$(basename "$file")` - this is only for defensive programming; it gets the actual name of the file
- `filename=${filename%.*}` - this removes the extension from `filename`
- `convert $file $filename.tif` - runs your actual convert command
Problem
I need to write a shell script to convert the image format from .png to .tif. The script is as follows: ``` #!/bin/sh for f in `ls *.png` do convert $f $f.tif done ``` But doing this will append the .tif format to the existing filename. ie if the image is abc.png the $f will have abc.png and after converting the filename becomes abc.png.tif. This is not what I want. I need it to be abc.tif. How do I manipulate $f to remove .png?