raquela
raquela

Reputation: 268

changing the name of many files by increasing the number

I want to change the file names from a terminal. I have many files, so I cannot change all of them one by one.

a20170606_1257.txt -> a20170606_1300.txt
a20170606_1258.txt -> a20170606_1301.txt

I am only able to change it by:

rename 57.txt 00.txt *57.txt

but it is not enough.

Upvotes: 0

Views: 55

Answers (2)

Shakiba Moshiri
Shakiba Moshiri

Reputation: 23774

Perl e flag to rescue

rename -n -v  's/(?<=_)(\d+)/$1+43/e' *.txt

test

 dir $  ls | cat -n
     1  a20170606_1257.txt
     2  a20170606_1258.txt
 dir $  
 dir $  
 dir $  rename -n -v  's/(?<=_)(\d+)/$1+43/e' *.txt
rename(a20170606_1257.txt, a20170606_1300.txt)
rename(a20170606_1258.txt, a20170606_1301.txt)
 dir $  
 dir $  rename -v  's/(?<=_)(\d+)/$1+43/e' *.txt
a20170606_1257.txt renamed as a20170606_1300.txt
a20170606_1258.txt renamed as a20170606_1301.txt
 dir $  
 dir $  ls | cat -n
     1  a20170606_1300.txt
     2  a20170606_1301.txt
 dir $  

rename_with_e_flag


rename --help:  
Usage:
    rename [ -h|-m|-V ] [ -v ] [ -n ] [ -f ] [ -e|-E *perlexpr*]*|*perlexpr*
    [ *files* ]

Options:
    -v, -verbose
            Verbose: print names of files successfully renamed.

    -n, -nono
            No action: print names of files to be renamed, but don't rename.

    -f, -force
            Over write: allow existing files to be over-written.

    -h, -help
            Help: print SYNOPSIS and OPTIONS.

    -m, -man
            Manual: print manual page.

    -V, -version
            Version: show version number.

    -e      Expression: code to act on files name.

            May be repeated to build up code (like "perl -e"). If no -e, the
            first argument is used as code.

    -E      Statement: code to act on files name, as -e but terminated by

Upvotes: 1

Inian
Inian

Reputation: 85550

Just playing with parameter expansion to extract the longest and shortest strings of type ${str##*} and ${str%%*}

offset=43
for file in *.txt; do 
    [ -f "$file" ] || continue
    woe="${file%%.*}"; ext="${file##*.}"
    num="${woe##*_}"
    echo "$file" "${woe%%_*}_$((num+offset)).${ext}"
done

Once you have it working, remove the echo line and replace it with mv -v. Change the offset variable as you wish, depending on where you want to start your re-named files from.

Upvotes: 1

Related Questions