Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

replacing text in file

Status
Not open for further replies.

kirstenx

Technical User
Jan 23, 2015
1
NL
I'm very new to AWK. Who can help me with a simple code to do this:
Read a file temp.txt
If the file contains the word "apple", change all words "red" into the word "blue" and if the file contains the word "berry", change all words "yellow" into the word "green"
Overwrite the file temp.txt

Regards,
kirstenx
 
AWK isn't best used to do "inplace" substitutions in files. The closest to that would be something like redirecting the output to a tmp file, and then over-write the original...
Code:
#!/bin/bash
# awk.sh
infil="./awk.data"
awk '/apple/ { gsub(/red/, "blue") } /berry/ { gsub(/yellow/, "green") }1' $infil >  "$infil.tmp" && cp "$infil.tmp" $infil
 
Here's a solution, but it might not be allowed if the instructor specifically wants you to use awk. Grep for "apple" or whatever the keyword is in the file. If grep finds apple, use sed to do a global replace within the file. Same for "berry". Else don't do anything.

==================================
adaptive uber info galaxies (bigger, better, faster than agile big data clouds)


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top