Navigation Menu

Currently the navigation bar is not functioning. Use the Blog Archive or the Google Custom Search to find content.

Tuesday 25 June 2013

Shell script to rename files based on suffix

Given below is a Shell script to rename files based on suffix.

Links that you may find important :

http://linux.about.com/od/commands/l/blcmdl1_ls.htm
http://en.wikipedia.org/wiki/Ls
http://linux.about.com/library/cmd/blcmdl1_wc.htm
http://www.computerhope.com/unix/uwc.htm
http://en.wikipedia.org/wiki/Wc_%28Unix%29
http://en.wikipedia.org/wiki/Cut_%28Unix%29
http://linux.about.com/od/commands/l/blcmdl1_cut.htm
http://linux.about.com/library/cmd/blcmdln_expr.htm
http://en.wikipedia.org/wiki/Expr

Code :
#!/bin/sh 
if [ $# -ne 2 ]
then
    echo "Please enter 2 arguments"
    exit
fi

echo "files with suffix $1"
ls *$1
suffix_len=`echo $1|wc -c`
echo "suffix length = $suffix_len"
filelist=`ls *$1`
echo $filelist
num_of_files=`echo $filelist| wc -w`
echo $num_of_files

c=1
while [ $c -le $num_of_files ]
do
    file_name=`echo $filelist| cut -d" " -f$c`
    echo "File Name = $file_name"
    file_len=`echo $file_name| wc -c`
    echo "Filename Length = $file_len"
    n=`expr $file_len - $suffix_len`
    echo "n = $n"
    file_prefix=`echo $file_name| cut -c1-$n`
    echo "Prefix of File = $file_prefix"
    mv $file_name $file_prefix$2
    c=`expr $c + 1`
done
filelist=`ls *$1`
echo $filelist
Output :
files with suffix txt
a.txt btxt ctxt
suffix length = 4
a.txt btxt txt
3
File Name = a.txt
Filename Length = 6
n = 2
Prefix of File = a.
File Name = btxt
Filename Length = 5
n = 1
Prefix of File = b
File Name = ctxt
Filename Length = 5
n = 1
Prefix of File=c
a.text btext ctext

Note : Leave a comment if you feel the program is incorrect and/or has errors and/or if the program and its output don't match. Please report about broken links.

No comments:

Post a Comment