Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A script to change file names

Tags:

echo

sed

awk

I am new to awk and shell based programming. I have a bunch of files name file_0001.dat, file_0002.dat......file_1000.dat. I want to change the file names such as the number after file_ will be a multiple of 4 in comparison to previous file name. SO i want to change

file_0001.dat to file_0004.dat
file_0002.dat to file_0008.dat 

and so on.

Can anyone suggest a simple script to do it. I have tried the following but without any success.

#!/bin/bash
a=$(echo $1 sed -e 's:file_::g' -e 's:.dat::g')
b=$(echo "${a}*4" | bc)
shuf file_${a}.dat > file_${b}.dat
like image 250
user3720427 Avatar asked Jun 08 '14 20:06

user3720427


1 Answers

This script will do that trick for you:

#!/bin/bash
for i in `ls -r *.dat`; do
    a=`echo $i | sed 's/file_//g' | sed 's/\.dat//g'`
    almost_b=`bc -l <<< "$a*4"`
    b=`printf "%04d" $almost_b`
    rename "s/$a/$b/g" $i
done

Files before:

file_0001.dat file_0002.dat

Files after first execution:

file_0004.dat file_0008.dat

Files after second execution:

file_0016.dat file_0032.dat

like image 157
Jacek Sokolowski Avatar answered Sep 30 '22 15:09

Jacek Sokolowski