Reputation: 74
I have a lot of jpg files with letters and numbers in their names. I want to remove all letters, for example abc12d34efg.jpg
becomes 1234.jpg
. For the for loop I thought:
for i in *.jpg; do mv "$i" ...
but I can't find a command for what I want.
Upvotes: 0
Views: 40
Reputation: 17169
Here is a oneline solution that uses tr
for f in *.jpg ; do n="$(echo ${f} | tr -d a-zA-Z )" ; mv "$f" "${n}jpg" ; done
With some formatting it would look like as
for f in *.jpg ; do
n="$(echo ${f} | tr -d a-zA-Z )"
mv "$f" "${n}jpg"
done
Here is what's happening:
First we remove all letters from the name using tr -d a-zA-Z
. From abc12d34efg.jpg
we get 1234.
(with a dot at the end as .
does not belong in the a-z
and A-Z
intervals) and assign this value to variable $n
. T
Then we can rename $f
to ${n}jpg
. That's it.
Update to delete both lower case and upper case letters use tr -d a-zA-Z
, to delete only lower case letters use tr -d a-z
instead.
Upvotes: 0
Reputation: 53674
You can use sed to replace all letters with nothing using regex.
for i in *.jpg; do mv $i `echo $i | sed -e 's/[a-zA-Z]//g'`jpg; done
Upvotes: 1
Reputation: 52142
With shell parameter expansion:
for fname in *.jpg; do mv "$fname" "${fname//[[:alpha:]]}jpg"; done
"${fname//[[:alpha:]]}"
is a substitution of all occurrences of [[:alpha:]]
(any letter) with nothing. Because this also removes the jpg
, we have to add it again – the appended jpg
does that.
Upvotes: 1