简体   繁体   English

Bash命令从所有文件名中删除前导零

[英]Bash command to remove leading zeros from all file names

I have a directory with a bunch of files with names like: 我有一个目录,其中包含一堆名称如下的文件:

001234.jpg
001235.jpg
004729342.jpg

I want to remove the leading zeros from all file names, so I'd be left with: 我想从所有文件名中删除前导零,所以我将留下:

1234.jpg
1235.jpg
4729342.jpg

I've been trying different configurations of sed, but I can't find the proper syntax. 我一直在尝试不同的sed配置,但我找不到合适的语法。 Is there an easy way to list all files in the directory, pipe it through sed, and either move or copy them to the new file name without the leading zeros? 有没有一种简单的方法可以列出目录中的所有文件,通过sed管道,然后将它们移动或复制到新文件名而不带前导零?

sed by itself is the wrong tool for this: you need to use some shell scripting as well. sed本身就是错误的工具:你还需要使用一些shell脚本。

Check Rename multiple files with Linux page for some ideas. 检查使用Linux页面重命名多个文件以获取一些想法。 One of the ideas suggested is to use the rename perl script: 建议的一个想法是使用rename perl脚本:

rename 's/^0*//' *.jpg
for FILE in `ls`; do mv $FILE `echo $FILE | sed -e 's:^0*::'`; done

In Bash, which is likely to be your default login shell, no external commands are necessary. 在Bash中,可能是您的默认登录shell,不需要外部命令。

shopt -s extglob
for i in 0*[^0]; do mv "$i" "${i##*(0)}"; done

Try using sed , eg: 尝试使用sed ,例如:

sed -e 's:^0*::'

Complete loop: 完整循环:

for f in `ls`; do
   mv $f $(echo $f | sed -e 's:^0*::')
done

Maybe not the most elegant but it will work. 也许不是最优雅但它会起作用。

for i in 0*
do
mv "${i}" "`expr "${i}" : '0*\(.*\)'`"
done

I dont know sed at all but you can get a listing by using find : 我根本不知道sed,但你可以使用find一个列表:

find -type f -name *.jpg

so with the other answer it might look like 所以用另一个答案可能看起来像

find . -type f -name *.jpg | sed -e 's:^0*::'

but i dont know if that sed command holds up or not. 但我不知道该sed命令是否成立。

Here's one that doesn't require sed : 这是一个不需要sed

for x in *.jpg ; do let num="10#${x%%.jpg}"; mv $x ${num}.jpg ;  done

Note that this ONLY works when the filenames are all numbers. 请注意,仅当文件名是所有数字时,此方法才有效。 You could also remove the leading zeros using the shell: 您还可以使用shell删除前导零:

for a in *.jpg ; do dest=${a/*(0)/} ; mv $a $dest ; done

In Bash shell you can do: 在Bash shell中,您可以:

shopt -s nullglob
for file in 0*.jpg
do
   echo mv "$file" "${file##*0}"
done

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

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