I have a file, foo.txt, and a regexp I want to find in that file. Each time I find the regexp, I want to take a line from another file, bar.txt, and substitute it in for the regexp match I found in foo.txt. Basically I want to do find/replace, but each time I replace I want the next replacement text to come from the next line in bar.txt.

Is there any easy shell magic to do this?

  • I find your problem definition very difficult to follow. Do you have examples of inputs/outputs?
    – Chris Down
    Commented Nov 12, 2012 at 20:51
  • @ChrisDown: Sorry about that, I've rephrased, think it's clearer now. Commented Nov 12, 2012 at 20:59
  • Do you want the entire line replaced, or just what the regular expression matches within the line? Commented Nov 13, 2012 at 16:34
  • @Omnifarious: Just what the regex matches Commented Nov 14, 2012 at 22:07

2 Answers 2


If I understand correctly, maybe something like:

awk '{getline repl < "second-file"; sub(/regexp/, repl); print}' < first-file

Or if regexp may appear several times per line or not on every line:

perl -pe 's/regexp/chomp($r=<STDIN>);$r/ge' first-file < second-file
perl -pe '
    BEGIN {
        open IN, "<replacements" or die $!;

        $tmp = <IN>;
        chomp $tmp;
' filename
  • 1
    From the problem description it sounds like maybe the pattern will have to be modified to `^.*(?:pattern).*$' because I think the person asking the question wants the entire line replaced. But otherwise this is an excellent answer. Commented Nov 12, 2012 at 21:16
  • 1
    I don't think so, actually. The question was clearer on this point before it was edited, though, so perhaps the OP can clarify if they did want to replace entire lines.
    – user20460
    Commented Nov 13, 2012 at 13:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .