Bash command to remove leading zeros from all file names

泄露秘密 提交于 2019-12-04 12:15:44

问题


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?


回答1:


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



回答2:


sed by itself is the wrong tool for this: you need to use some shell scripting as well.

Check Rename multiple files with Linux page for some ideas. One of the ideas suggested is to use the rename perl script:

rename 's/^0*//' *.jpg



回答3:


In Bash, which is likely to be your default login shell, no external commands are necessary.

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



回答4:


Try using sed, e.g.:

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

Complete loop:

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



回答5:


I dont know sed at all but you can get a listing by using 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.




回答6:


Here's one that doesn't require 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:

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



回答7:


Maybe not the most elegant but it will work.

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



回答8:


In Bash shell you can do:

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


来源:https://stackoverflow.com/questions/2074687/bash-command-to-remove-leading-zeros-from-all-file-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!