Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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

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

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.

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

Maybe not the most elegant but it will work.

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

In Bash shell you can do:

shopt -s nullglob
for file in 0*.jpg
do
   echo mv "$file" "${file##*0}"
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top