Unix Shell Script Assignment: Stage 1: Create a directory ~/UnixCourse/scriptAss
ID: 3918746 • Letter: U
Question
Unix Shell Script Assignment:
Stage 1:
Create a directory ~/UnixCourse/scriptAsst.
Within that directory, create a shell script, chExt1.sh taking two parameters:
A. the desired file extension
B. the name of a single file to be renamed with that extension
For example, (assuming you have cd’d into your scriptAsst directory,
should rename the file “aardvark.CPP” to “aardvark.cpp”.
should rename the file “bongo.dat” to “bongo.backup”.
Hint: Try to get the current name of the file into a shell variable (e.g., $oldName). Then use a sed command to rewrite that value to remove the file extension, and store the result in a second shell variable (e.g., $newName). Then append the desired new extension onto that. Finally, issue the actual command to rename the file. There are probably other ways to achieve this effect as well, but all of the info you need for the approach suggested here has been covered in the Lecture Notes.
Stage 2:
To make the script a bit more robust, it would be good if it checked to see if the file that we want to rename actually exists.
Within the same directory, create a shell script, chExt2.sh taking the same two parameters, that behaves the same as the first script for files that exists, but for files that do not exist, prints a message
fileName: No such file
where fileName is the name of the file given in the second parameter.
No other messages should be issued, including error messages from commands invoked by your script.
Stage 3:
Finally, within the same directory, create a shell script, chExt.sh that takes one or more parameters, where the first is a desired extension and the remainder are names of files to be renamed. For each file in the command line, this script should rename the file, as above, if the file exists or print the error message described in the previous step if the file does not exist.
For example,
should result in crocodile.foo being renamed crocodile.dat, an error message “bogusName.foo: No such file”, and dingo.bar being renamed dingo.dat.
Explanation / Answer
I had solved 2 questions.
Stage 1:
clear
oldName=$2
newName=$(echo $oldName|sed 's/.[^.]*$//')
newName=$newName.$1
mv $oldName $newName
Stage 2:
clear
oldName=$2
if test -f $oldName
then
newName=$(echo $oldName|sed 's/.[^.]*$//')
newName=$newName.$1
mv $oldName $newName
else
echo "$oldName: No such file"
fi
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.