Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux shell script to add leading zeros to file names

I have a folder with about 1,700 files. They are all named like 1.txt or 1497.txt, etc. I would like to rename all the files so that all the filenames are four digits long.

I.e., 23.txt becomes 0023.txt.

What is a shell script that will do this? Or a related question: How do I use grep to only match lines that contain \d.txt (i.e., one digit, then a period, then the letters txt)?

Here's what I have so far:

for a in [command i need help with] do   mv $a 000$a done 

Basically, run that three times, with commands there to find one digit, two digits, and three digit filenames (with the number of initial zeros changed).

like image 267
David Oneill Avatar asked Sep 08 '10 22:09

David Oneill


People also ask

How do I rename all files in a folder sequentially?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

Can Linux file names start with a number?

Numbers in file names is not an issue but you can't start feature class names with numbers: gis.stackexchange.com/questions/6686/…


1 Answers

Try:

for a in [0-9]*.txt; do     mv $a `printf %04d.%s ${a%.*} ${a##*.}` done 

Change the filename pattern ([0-9]*.txt) as necessary.


A general-purpose enumerated rename that makes no assumptions about the initial set of filenames:

X=1; for i in *.txt; do   mv $i $(printf %04d.%s ${X%.*} ${i##*.})   let X="$X+1" done 

On the same topic:

  • Bash script to pad file names
  • Extract filename and extension in bash
like image 59
Colin Hebert Avatar answered Sep 28 '22 00:09

Colin Hebert