TOPIC: Shell Scripts I am working on a 3 part problem and I have successfully co
ID: 3575814 • Letter: T
Question
TOPIC: Shell Scripts
I am working on a 3 part problem and I have successfully completed the first 2 parts but can't figure out the third part for the life of me
Part 3 Question:
Generalize your subst2 script, producing a new script subst that will apply a substitution to any number of files given on the command line. For example
should apply the same substitution throughout each of the three files named there (replaces all occurences of the word "foo" with "bar" in the given files)
This is the code I have that is incorrect:
#!/bin/sh
p1="$1"
shift
p2="$1"
shift
for file in $*
do
if grep "$p1" "$file" > /dev/null;then
mv "$file" "$file.bak"
sed "s/$p1/$p2/g" "$file.bak" > "$file"
fi
done
The error message I get from the professors verification tool reads:
Checking stage 3
grep: king: No such file or directory
grep: king: No such file or directory
grep: mouse.a: No such file or directory
grep: b: No such file or directory
Failed when running: ./subst 'l' 'ww' 'aardvark.cpp' 'bongo.dat' 'cat.dog.bak' 'emu.fish.txt' '../scriptAsst/gecko.cpp' '/home/user/UnixCourse/scriptAsst/hippo.cpp' '/home/user/UnixCourse/scriptAsst/../ibex.txt' 'jay.23' 'king cobra.dat' 'mouse.a b'
A backup file was not created or was mis-named.
Any advice as to why the verification tool doesnt like my answer would be greatly appreciated.
Explanation / Answer
Below is the required script.
#!/bin/bash
find = $1
replace = $2
shift
shift
if [ $# -gt 0 ] ;then
for filename in "$@" ; do
sed "s/$find/$replace/g" "$filename"
done
fi
Explanation :-
1). Initially the control is on argument1. So, `shift` command forwards the control to next argument.
2). "$@" - It refer to whole of command line text of arguments. Initially it will be below in statement mentioned in question.
foo bar myFile1.txt myFile2.txt myFile3.txt
After using `shift` twice. It will be
myFile1.txt myFile2.txt myFile3.txt
3). Usage of `sed` i pretty clear with the names used.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.