Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The Linux script for this assignment is find_and_replace.sh. You will need to us

ID: 672763 • Letter: T

Question

The Linux script for this assignment is find_and_replace.sh. You will need to use sed to replace all instances of one string in a file. Specifically, find_and_replace.sh should take 4 arguments. The first is the file to read from, the second is the file to output to, the third is the string to find, and the fourth is the replacement string. The script itself is relatively simple. The script must read every line from the input file no matter how many lines there are. It then replaces all instances of the first string given with the second string. Finally, it outputs every line to the output file whether or not any substitutions happened.

As always you need to do error checking. Specifically, check the number of arguments and that the first argument is actually a file. Note that you don't need to check if the second argument exists or because your script should output to that file either way. In addition, you'll need a way to send the input file in to a loop to read every line of that file. You can use I/O redirection with the entire loop. The same idea will be used to send the output of the loop to the output file. Here is some example output:

   [user@localhost joe]$ ./find_and_replace.sh
   usage: find_and_replace.sh existing_file new_file current_string new_string
   [user@localhost joe]$ cat jedi_code
   Jedi code:
   There is no emotion, there is peace.
   There is no ignorance, there is knowledge.
   There is no passion, there is serenity.
   There is no chaos, there is harmony.
   There is no death, there is the Force.
   [user@localhost joe]$ ./find_and_replace.sh jedi_code jedi.out "is no" "ain't"
  [user@localhost joe]$ cat jedi.out
  Jedi code:
   There ain't emotion, there is peace.  
   There ain't ignorance, there is knowledge.   
   There ain't passion, there is serenity.   
   There ain't chaos, there is harmony.
   There ain't death, there is the Force.
   [user@localhost joe]$

This is the code that i have but it is not working. Any help?

. Find_and_replace

if [ "$#" -ne 4 ]; then

echo "We need four arguments!" >&2

exit 1

else

// Here I have given the file name directly

sed -e 's/”$3”/”$4”/g' $1 >> $2

//to read every line, you can use this code

IFS=$' '; for line in $(cat “$1”.txt); do

sed -e 's/”$3”/”$4”/g' $line > $2

done

fi

Explanation / Answer

#!/bin/sh

if [ "$#" -ne 4 ] # if there are no 4 parameters offered.
then
echo "We need four arguments!" >&2 #Display an error message.
else               #else
sed -e s/"$3"/"$4"/g $1 >> $2   #Replace all occurrences of 3rd argument with 4th argument.
fi

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote