Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

replacing text in file

replacing text in file

replacing text in file

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


RE: replacing text in file

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 -->

# awk.sh
awk '/apple/ { gsub(/red/, "blue") } /berry/ { gsub(/yellow/, "green") }1' $infil >  "$infil.tmp" && cp "$infil.tmp" $infil 

RE: replacing text in file

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)

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close