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
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.
7. That's funny! :) +11, you could +1, now I used 7, you should +7 :) no special reason, I like that number..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.