5

The code below replaces the first occurrence of apple with banana. How do I achieve the same using awk / gawk?

sed -i "0,/apple/s//banana/" myfile.txt

1 Answer 1

9

this is what I come up with:

awk '!x{x=sub("apple","banana")}7' file

for example:

kent$  cat f
foo
apple
foo
apple
apple

kent$  awk '!x{x=sub("apple","banana")}7' f
foo
banana
foo
apple
apple

for the sed -i (change in place) part, if you use gawk 4.1.0, you have that option too. otherwise, you have to use a temp file.

Sign up to request clarification or add additional context in comments.

19 Comments

you are using the 7. That's funny! :) +1
@hek2mgl if I used 1, you could +1, now I used 7, you should +7 :) no special reason, I like that number..
@MohammedNoureldin because non-zero number does default action in awk: print
@MohammedNoureldin no difference. I prefer right index finger, so I picked 7
OK to help the others, another form of the command to make it more readable: awk '!x{x=sub("apple","banana")}{print $0}' test. substituting {print} with a number (any thing other than 0 is true), makes {print} to be true (even is not written). This syntax !x{...} means: if x != false (i.e. if it has a value) do something. The rest should be clear for any essential knowledge programmer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.