简体   繁体   English

通过删除字母从外壳重命名文件

[英]Renaming files from shell by removing letters

I have a lot of jpg files with letters and numbers in their names. 我有很多jpg文件,其名称中包含字母和数字。 I want to remove all letters, for example abc12d34efg.jpg becomes 1234.jpg . 我想删除所有字母,例如abc12d34efg.jpg变成1234.jpg For the for loop I thought: 对于for循环,我认为:

 for i in *.jpg; do mv "$i" ...

but I can't find a command for what I want. 但是我找不到想要的命令。

With shell parameter expansion: 使用shell参数扩展:

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. "${fname//[[:alpha:]]}"将所有出现的[[:alpha:]] (任何字母)替换为空。 Because this also removes the jpg , we have to add it again – the appended jpg does that. 因为这也会删除jpg ,所以我们必须再次添加它-附加的jpg

您可以使用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 这是一个使用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 . 首先,我们使用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 . abc12d34efg.jpg我们得到1234. (在末端的一个点.不会在属于azAZ间隔),并指定这个值变量$n T Ť

Then we can rename $f to ${n}jpg . 然后,我们可以将$f重命名$f ${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. 更新以删除小写字母和大写字母,请使用tr -d a-zA-Z ,仅删除小写字母,请使用tr -d az

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM