Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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

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
share|improve this answer
perl -pe '
    BEGIN {
        open IN, "<replacements" or die $!;

        $tmp = <IN>;
        chomp $tmp;
' filename
share|improve this answer
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
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. – snailplane Nov 13 '12 at 13:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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