1

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?

4
  • I find your problem definition very difficult to follow. Do you have examples of inputs/outputs? – Chris Down Nov 12 '12 at 20:51
  • @ChrisDown: Sorry about that, I've rephrased, think it's clearer now. – Joseph Garvin Nov 12 '12 at 20:59
  • Do you want the entire line replaced, or just what the regular expression matches within the line? – Omnifarious Nov 13 '12 at 16:34
  • @Omnifarious: Just what the regex matches – Joseph Garvin Nov 14 '12 at 22:07
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
2
perl -pe '
    BEGIN {
        open IN, "<replacements" or die $!;
    }

    s/pattern/
        $tmp = <IN>;
        chomp $tmp;
        $tmp
    /xe;
' filename
2
  • 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. – Omnifarious Nov 12 '12 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 Nov 13 '12 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.