In: Computer Science
Consider that you want to rename all files of a given type (e.g. file extension) to a different filetype. For example, you want to change the file extension of all txt files to text. Write a shell script rename.sh (3%) that:
Explanation :
1) Check for the no of arguments
if [ $# -ne 2
];then
echo "Provide two args [file 1: the original file] [file 2 : file
name that the original file needs to be changed
to]"
exit
1
fi
checks for whether the no of args provided is atleast two or
not
2) File Check : It checks whether the file to be renamed is present
or not along with the extension check
Note : I have made check for only .txt
if [ -f "$file"
]
then
if [ ${file: -4} == ".txt"
]
then
echo "file extension is
.txt"
else
echo "file extension should be .txt
only"
fi
echo "$file
found"
else
echo "$file not
found"
exit
1
fi
3) Check for Read and Write Permissions : The below code checks
whether the file to be renamed has write and read
permissions.
if [ -w $1 ] &&
W="Write"
then
echo "$file is having write
permission"
else
echo "$file is not having write
permission"
exit
1
fi
if [ -r $1 ] &&
R="Read"
then
echo "$file is not having read
permission"
exit
1
fi
4) Renaming File using sed command
for filename in $1;
do
newFilename=$(sed -E
's#img_([0-9]{1,2})-([0-9]{1,2})-([0-9]{1,2})_(.*)$#newyears_20\3-\2-\1_\4#'
<<<
"$2")
mv "$1"
"$newFilename"
echo "File has been renamed
successfully"
done
Steps to be followed :
Step 1 : Open vi editor or any other editor based on the linux
system you are using and copy the following content into the file
rename.sh
if [ $# -ne 2
];then
echo "Provide two args [file 1: the original file] [file 2 : file
name that the original file needs to be changed
to]"
exit
1
fi
file=$1
if [ -f "$file"
]
then
if [ ${file: -4} == ".txt"
]
then
echo "file extension is
.txt"
else
echo "file extension should be .txt
only"
fi
echo "$file
found"
else
echo "$file not
found"
exit
1
fi
if [ -w $1 ] &&
W="Write"
then
echo "$file is having write
permission"
else
echo "$file is not having write
permission"
exit
1
fi
if [ -r $1 ] &&
R="Read"
then
echo "$file is not having read
permission"
exit
1
fi
for filename in $1;
do
newFilename=$(sed -E
's#img_([0-9]{1,2})-([0-9]{1,2})-([0-9]{1,2})_(.*)$#newyears_20\3-\2-\1_\4#'
<<<
"$2")
mv "$1"
"$newFilename"
echo "File has been renamed
successfully"
done
Step 2 : execute the command ./rename.sh file.txt file.text
Step 3 : Kindly execute the above command for various test cases
that is mentioned in the problem description.
Output:
sh-4.4$ ./rename.sh file.txt
file.text
file extension is
.txt
file.txt
found
file.txt is having write
permission
file.txt is having read
permission
File has been renamed
successfully
sh-4.4$ vi rename.sh