Bash 命令从所有文件名中删除前导零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2074687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash command to remove leading zeros from all file names
提问by George
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. 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 Simon Nickerson
sedby itself is the wrong tool for this: you need to use some shell scripting as well.
sed本身就是错误的工具:您还需要使用一些 shell 脚本。
Check Rename multiple files with Linuxpage for some ideas. One of the ideas suggested is to use the renameperl script:
检查使用 Linux页面重命名多个文件以获取一些想法。建议的想法之一是使用renameperl 脚本:
rename 's/^0*//' *.jpg
回答by cyborg
for FILE in `ls`; do mv $FILE `echo $FILE | sed -e 's:^0*::'`; done
回答by ephemient
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
回答by eduffy
Try using sed, e.g.:
尝试使用sed,例如:
sed -e 's:^0*::'
Complete loop:
完整循环:
for f in `ls`; do
mv $f $(echo $f | sed -e 's:^0*::')
done
回答by jml3310
Maybe not the most elegant but it will work.
也许不是最优雅的,但它会起作用。
for i in 0*
do
mv "${i}" "`expr "${i}" : '0*\(.*\)'`"
done
回答by prodigitalson
I dont know sed at all but you can get a listing by using find:
我根本不知道 sed,但您可以使用find以下命令获取列表:
find -type f -name *.jpg
find -type f -name *.jpg
so with the other answer it might look like
所以对于另一个答案,它可能看起来像
find . -type f -name *.jpg | sed -e 's:^0*::'
find . -type f -name *.jpg | sed -e 's:^0*::'
but i dont know if that sed command holds up or not.
但我不知道该 sed 命令是否成立。
回答by ghostdog74
In Bash shell you can do:
在 Bash shell 中,您可以执行以下操作:
shopt -s nullglob
for file in 0*.jpg
do
echo mv "$file" "${file##*0}"
done
回答by Kaleb Pederson
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

