Search code examples
bashloops

A bash script that creates a file, writes into the it then searches and replaces words in the file


new at this, so any suggestions would be great!

I'm trying to create a file, input the contents of the file,show the file and finally then search and replace words in that file and display the contents again.

The file should contain the following:

Write a bash script
To show off 
Your scripting skills
Then show the results 

Search and replace the words “Your” with “My” and the word “Then” with “Now”

So far Ive got:

#Check if the file exits and create if not (im not sure if there is a better way to do this)
if [ ! -e "NewFile.txt" ]; then
    touch NewFile.txt
fi

#Ask user for input
echo "Input the content of the file:"

#Display the file the first time
cat NewFile.txt

#load what's in the file into an array. 
not sure what to put here 

#search and replace “Your” with “My” and the word “Then” with “Now”
not sure what to put here 


#display the file after words have been replaced
cat NewFile.txt

Solution

  • Do

    sed -i 's/Your/My/g' input.txt && sed -i 's/Then/Now/g' input.txt
    

    Which replace the first wort with the second word, editing the file. I have two commands to achieve it, one is for the first replace and the second is for the second replace, separated via &&.