Alex
Alex

Reputation: 1447

How to change file name in loop?

I have files in folder /root

file0001
file0002
file0010
file0011
file0100
file0121

I have this code

for (( i=1; i<=1000; i++))
do
file='/root/file'$i
done

I need to to change file name in loop

file0001 --> file1
file0010 --> file10
file0100 --> file100

Any ideas?

Upvotes: 0

Views: 2781

Answers (4)

Scrutinizer
Scrutinizer

Reputation: 9926

Try:

cd /root
for f in file*
do
  echo mv "$f" "${f%%[0-9]*}${f#"${f%%[1-9]*}"}"
done

Remove the echo if OK...

Upvotes: 1

mfo
mfo

Reputation: 152

top remove trailing zeros from the number part of your filenames use:

rename 's/^file0*/file/' file*

Upvotes: 0

kometonja
kometonja

Reputation: 447

If you want to trim leading zeros, simple bash script can do the trick:

#!/bin/bash
while read line           
do           
    name=`echo $line | cut -c5- | sed 's/^[0]*//'`
    echo "file$name"
done <your_file.txt

result: ....
file0100->file100
file0121->file121

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

You could use the printf command:

file=$(printf "/root/file%04d" $i)

Upvotes: 3

Related Questions