Modifying several files in UNIX
From Antalya
There are many times when you have to do modifications on a bunch of files. For smaller number (<10) you may be tempted to do this one by one, but your UNIX shell gives you plenty of opportunities to do the job more efficiently.
Using shell loops
Basically this lets you choose files based on a pattern and for each of these files do something.
Here is one example, we will look for all the files that have the extension .JPG
and scale them using convert. In this case, we are trying to reduce the size of the image files, so that we do not overwrite them we use a small trick, and rename the file into _sml.jpg
. So that even if we run the script twice the newly generated files will not interfere. We use the basename
command to extract the file name for this.
#! /bin/tcsh
foreach i (*.JPG)
set j=`basename $i .JPG`
echo "Processing $j"
convert -scale 1920x1920 -quality 85 $i ${j}_sml.jpg
end
#!/bin/bash
for i in *.JPG
do
j=$(basename $i .JPG)
echo "Processing $j"
convert -scale 1920x1920 -quality 85 $i ${j}_sml.jpg
done