I would like to know how can I replace the first occurrence of searched pattern in the entire file.For example,
import java.io.File;
import java.io.File;
should be replaced by
import java.io.IOException;
import java.io.File;
How do I achieve this using sed ? Thank You
There’s certainly no need to write some big long script when it only takes on substitution to do all the work in one line. You just have to pick the right Power Tool for the job.
Here’s a Perl one-liner:
% cat -n /tmp/f
1 import java.lang.Character;
2 import java.io.File;
3 import java.io.File;
4 import java.util.Pattern;
% perl -pe 's//IoException/ if m?import java\.io\.\KFile?' /tmp/f
import java.lang.Character;
import java.io.IoException;
import java.io.File;
import java.util.Pattern;
And if you want to do it with an edit of the file, just add -i.bak:
% perl -i.bak -pe 's//IoException/ if m?import java\.io\.\KFile?' /tmp/f
% head /tmp/f{,.bak}
==> /tmp/f <==
import java.lang.Character;
import java.io.IoException;
import java.io.File;
import java.util.Pattern;
==> /tmp/f.bak <==
import java.lang.Character;
import java.io.File;
import java.io.File;
import java.util.Pattern;
The reason that works is because when you give the m//
operator a ??
delimiter, it has some built-in state to remember to match the first time only.
Then in the substitute, the empty pattern means to reuse the last matched pattern, so you don’t have to type it again and risk the two ever divering.
Finally, the \K
in the pattern reneges on the match, “keeping” the stuff to the left, so that it doesn’t get gobbled by the substitute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With