Create a shell script, cExt.sh that takes one or more parameters, where the firs
ID: 3916792 • Letter: C
Question
Create a shell script, cExt.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, if the file exists or print the error message file does not exist.
For example,
ls > alligator.foo
echo meow > dango.bar
echo snake > "queen cobra.cpp"
./cExt.sh dat alligator.foo madeup.foo dango.bar queen cobra.cpp should result in alligator.foo being renamed alligator.dat, an error message “madeup.foo: No such file”, dango.bar being renamed dango.dat., and queen cobra.cpp being renamed to queen cobra.dat (This part is not what I'm having trouble with, it's only an example and the input is correct)
My only issue is the spacing in queen cobra.cpp and changing it from queen cobra.cpp to queen cobra.dat please help
this is what I have so far
#!/bin/sh
if [ $# -le 1 ] then
echo "Usage: $0 [file2 .... fileN]"
exit 1
fi
ext=$1
shift
oldName="$@"
for f in $oldName
do
if [ ! -f "$f" ] then
echo "$f: No such file"
else
sedTime=`echo $f | sed 's/.[^.]*$//'`
newName=$sedTime.$ext
if [ "$f" != "$newName" ] then
mv "$f" "$newName"
fi
fi
done
Explanation / Answer
#!/bin/sh
if [ $# -le 1 ]; then
echo "Usage: $0 [file2 .... fileN]"
exit 1
fi
ext=$1
shift
#oldName="$@"
for f in "$@"
do
if [ ! -f "$f" ]; then
echo "$f: No such file"
else
sedTime=`echo $f | sed 's/.[^.]*$//'`
newName=$sedTime.$ext
if [ "$f" != "$newName" ]; then
mv "$f" "$newName"
echo "file $f is renamed to file $newName"
fi
fi
done
The arguments should be pased as below;
./cExt.sh dat alligator.foo madeup.foo dango.bar "queen cobra.cpp"
Note the double quoutes in "queen cobra.cpp".
The double quotes is necessary to identify as a single string
The 'oldName' variable is not used. directly the argument variable "$@" is used
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.