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.
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.
您可以使用sed使用正则表达式将所有字母替换为空。
for i in *.jpg; do mv $i `echo $i | sed -e 's/[a-zA-Z]//g'`jpg; done
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 az
and AZ
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 az
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.