Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

first replacement of a string in a file using sed

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

like image 789
indira Avatar asked Apr 21 '11 09:04

indira


Video Answer


1 Answers

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.

like image 137
tchrist Avatar answered Sep 23 '22 16:09

tchrist